1

I have this array of json_decode:

"[{"pracetamol":"cabsol","bandol":"bottol"},{"2":"77","4":"99"}]"

dd for them :

enter image description here

I need to arranging them like that:

pracetamol - cabsol - 2 - 77

bandol - bottol - 4 - 99

I used this code but does not work like what I need:

$decoded = json_decode($doctor->pharmacys, true);

@foreach($decoded as $d)

  @foreach($d as $k => $v) 
    {{"$k - $v\n"}} <br>
  @endforeach

@endforeach
Tim Lewis
  • 27,813
  • 13
  • 73
  • 102

3 Answers3

0

You can use this code to arrange your data better:

$decoded = json_decode($doctor->pharmacys, true);
$result = [];
foreach($j as $k1 => $v1){
    $i=0;
    foreach($v1 as $k2 => $v2){
        isset($result[$i]) ? array_push($result[$i],$k2,$v2) : $result[$i] = [$k2,$v2];
        $i++;
    }
}

result:

Array
(
    [0] => Array
        (
            [0] => pracetamol
            [1] => cabsol
            [2] => 2
            [3] => 77
        )

    [1] => Array
        (
            [0] => bandol
            [1] => bottol
            [2] => 4
            [3] => 99
        )

)

in bade:

@foreach($result as $d)

  @foreach($d as $v) 
    {{$v}} @if(!$loop->last) - @endif
  @endforeach

  @if(!$loop->last) <br> @endif

@endforeach
Kamran
  • 523
  • 6
  • 18
0

You can do the following in PHP :

$a = '[{"pracetamol":"cabsol","bandol":"bottol"},{"2":"77","4":"99"}]';
$b = json_decode($a, true);
$k1 = array_keys($b[0]);
$k2 = array_keys($b[1]);

for ($i = 0; $i < count($k1); $i++) {
    echo $k1[$i]." - ".$b[0][$k1[$i]]." - ".$k2[$i]." - ".$b[1][$k2[$i]]."\n";
}

The trick here is to get the list of keys for each array (named $k1 and $k2 in my example). These lists should respect the same order as in the associative array. Further, if you need to have access to their index, you can use array_search as stated in this answer.

Marc
  • 1,350
  • 2
  • 11
  • 29
0

I play with Collection and Tinker Well and this is the best approach that I can come up with:

$array = [
    [
        'pracetamol' => 'cabsol',
        'bandol' => 'bottol'
    ],
    [
        '77' => 2,
        '99' => 4
    ]
];

$texts = collect($array[0])->map(function ($text, $key) {
    return "$key - $text";
});

$numbers = collect($array[1])->map(function ($number, $key) {
    return "$number - $key";
});

$texts
    ->zip($numbers)
    ->mapSpread(function ($linkedText, $linkedNumber) {
        return "$linkedText - $linkedNumber";
    })
    ->values()
    ->toArray();
Kevin Bui
  • 2,754
  • 1
  • 14
  • 15