Laravel 如何排列数组的数据?

Laravel 如何排列数组的数据?,laravel,Laravel,我有一个json_解码数组: "[{"pracetamol":"cabsol","bandol":"bottol"},{"2":"77","4":"99"}]" 对他们来说: 我需要这样安排他们: pracetamol - cabsol - 2 - 77 bandol - bottol - 4 - 99 我使用了此代码,但工作方式与我需要的不同: $decoded = json_decode($doctor->pharmacys, true); @foreach($decoded

我有一个json_解码数组:

"[{"pracetamol":"cabsol","bandol":"bottol"},{"2":"77","4":"99"}]"
对他们来说:

我需要这样安排他们:

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
$decoded=json\u decode($doctor->pharmacys,true);
@foreach($解码为$d)
@foreach($d为$k=>$v)
{{{$k-$v\n}}
@endforeach @endforeach
您可以使用此代码更好地排列数据:

$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
@foreach($d作为结果)
@foreach($d为$v)
{{$v}@if(!$loop->last)-@endif
@endforeach
@if(!$loop->last)
@endif @endforeach
您可以在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";
}
$a='[{“扑热息痛”:“卡布索”,“班多尔”:“博托尔”},{“2”:“77”,“4”:“99”}];
$b=json_解码($a,true);
$k1=数组_键($b[0]);
$k2=数组_键($b[1]);
对于($i=0;$i
这里的技巧是获取每个数组的键列表(在我的示例中命名为$k1和$k2)。这些列表的顺序应与关联数组中的顺序相同。 此外,如果您需要访问他们的索引,您可以使用
array\u search
,如本文所述。

$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();