我想根据公共列值合并两个数组。这是我的 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 得到了这个,但它看起来很丑。请告诉我更好的方法。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这可以在没有“丑陋的嵌套 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', ), )你可以尝试
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);