首页 > 解决方案 > 如何排列数组的数据?

问题描述

我有这个 json_decode 数组:

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

dd 为他们:

在此处输入图像描述

我需要像这样安排它们:

pracetamol - cabsol - 2 - 77

bandol - bottol - 4 - 99

我使用了这段代码,但不像我需要的那样工作:

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

@foreach($decoded as $d)

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

@endforeach

标签: laravel

解决方案


您可以使用此代码更好地排列数据:

$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++;
    }
}

结果:

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

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

)

在巴德:

@foreach($result as $d)

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

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

@endforeach

推荐阅读