我想根據公共列值合併兩個陣列。這是我的 2 個陣列:
$array1 = [ [ "total_process_per_category" => "6", "category_id" => "1" ], [ "total_process_per_category" => "2", "category_id" => "2" ] ]; $array2 = [ [ "total_pinned_per_category" => "16", "category_id" => "1" ], [ "total_pinned_per_category" => "4", "category_id" => "2" ] ];
我想合併這些陣列以獲得:
array ( 0 => array ( 'total_process_per_category' => '6', 'total_pinned_per_category' => '16', 'category_id' => '1', ), 1 => array ( 'total_process_per_category' => '2', 'total_pinned_per_category' => '4', 'category_id' => '2', ), )
如您所見,這兩個陣列具有相同的鍵 ['category_id'] 和相同的值。
我想要得到一個結果,其中 ['total_process_per_category'] 和 ['total_pinned_per_category'] 根據它們的 ['category_id'] 值一起放置在同一數組上。
我使用嵌套的 foreach 得到了這個,但它看起來很醜。請告訴我更好的方法。
P粉3669463802023-11-10 00:52:21
這可以在沒有「醜陋的巢狀 foreach」的情況下完成。在迭代之前合併兩個數組,按category_id 值進行分組。循環結束後,使用 array_values() 清除暫時的一級鍵。
程式碼:(示範) (array_reduce() 版本)
$result = []; foreach (array_merge($array1, $array2) as $row) { $result[$row['category_id']] = ($result[$row['category_id']] ?? []) + $row; } var_export(array_values($result));
輸出:
array ( 0 => array ( 'total_process_per_category' => '6', 'category_id' => '1', 'total_pinned_per_category' => '16', ), 1 => array ( 'total_process_per_category' => '2', 'category_id' => '2', 'total_pinned_per_category' => '4', ), )
P粉0717437322023-11-10 00:45:48
你可以嘗試array_reduce
:
$someVariable = 'someValue'; $result = array_reduce(array_merge($array1, $array2), function ($carry, $item) use ($someVariable) { if (isset($carry[$item['category_id']])) { $carry[$item['category_id']] = array_merge($carry[$item['category_id']], $item); } else { $carry[$item['category_id']] = $item; } return $carry; }, array()); var_dump($result);