PHP如何将两个数组合并为一个:同ID累加数量、新增不存在ID的项
按ID匹配累加数量的二维数组合并方案
直接用array_merge出问题的原因
array_merge的原生逻辑是将多个索引数组拼接为连续数字索引的新数组,不会对数组内部的子元素做id维度的匹配判断,因此会出现重复id的项独立留存的冗余结果,和预期的累加逻辑不符。
实现思路
- 用子元素的
id值作为临时结果集的键,建立id到元素的直接映射,避免嵌套遍历查找id的性能损耗 - 逐次遍历所有待合并的数组:
- 若当前元素的id已经存在于临时结果集,就累加对应项的
qty值 - 若id不存在,就直接将当前元素存入临时结果集
- 若当前元素的id已经存在于临时结果集,就累加对应项的
- 最后通过
array_values重置为连续数字索引,匹配需要的输出结构
核心代码实现
// 原始测试数组 $a1 = [ ["id" => 1, "qty" => 1], ["id" => 2, "qty" => 1] ]; $a2 = [ ["id" => 1, "qty" => 1] ]; // 初始化临时结果集,以id为键映射a1的元素 $tempResult = []; foreach ($a1 as $item) { $tempResult[$item['id']] = $item; } // 遍历a2做匹配累加 foreach ($a2 as $item) { $currentId = $item['id']; if (isset($tempResult[$currentId])) { $tempResult[$currentId]['qty'] += $item['qty']; } else { $tempResult[$currentId] = $item; } } // 重置为连续数字索引,得到最终输出 $output = array_values($tempResult); echo '<pre>'; print_r($output); echo '</pre>';
通用封装(支持任意数量数组合并)
如果后续需要合并2个以上的同类数组,可以把逻辑抽成可复用函数:
function mergeByIdAccumulateQty(array ...$sourceArrays): array { $tempResult = []; foreach ($sourceArrays as $sourceArray) { foreach ($sourceArray as $item) { $itemId = $item['id']; if (isset($tempResult[$itemId])) { $tempResult[$itemId]['qty'] += $item['qty']; } else { $tempResult[$itemId] = $item; } } } return array_values($tempResult); } // 调用示例 $output = mergeByIdAccumulateQty($a1, $a2);
性能说明:该实现的时间复杂度为O(n),仅需对所有待合并元素做一次遍历,相比嵌套循环匹配id的O(n²)方案,在数组规模较大时性能优势明显。
内容的提问来源于stack exchange,提问作者SHARKDEV
相关产品推荐
相关产品推荐

