如何将数组中同ID元素合并并累加number字段值?
合并数组中同ID元素并累加数值的实现方案(PHP为例)
嗨,这个需求其实很典型,核心思路就是利用数组键的唯一性来分组聚合,下面给你具体的实现代码和解释:
完整代码示例
// 你的原始数组 $originalArray = [ ['id' => '3412341233214', 'number' => 21000], ['id' => '12121212121212', 'number' => 18000], ['id' => '12121212121212', 'number' => 17000] ]; // 初始化临时数组,用id作为键来分组 $tempGroup = []; foreach ($originalArray as $item) { $currentId = $item['id']; // 如果当前id已经在临时数组里,就累加number if (isset($tempGroup[$currentId])) { $tempGroup[$currentId]['number'] += $item['number']; } else { // 不存在的话直接把当前元素放进去 $tempGroup[$currentId] = $item; } } // 把关联数组转回数字索引数组,就是你要的最终结构 $result = array_values($tempGroup); // 打印结果验证 print_r($result);
运行结果
执行后你会得到这样的数组:
Array ( [0] => Array ( [id] => 3412341233214 [number] => 21000 ) [1] => Array ( [id] => 12121212121212 [number] => 35000 ) )
逻辑说明
- 用
$tempGroup这个临时数组,把每个元素的id作为键——因为数组的键不能重复,所以天然帮我们完成了去重分组 - 遍历原数组时,检查当前
id是否已存在:存在就累加number值,不存在就新增条目 - 最后用
array_values()把临时数组的键重置为连续的数字索引,完全符合你要的结构
如果是用其他语言(比如JavaScript),思路也是一样的:用对象/Map来做分组键,然后遍历聚合数值就行。
内容的提问来源于stack exchange,提问作者user3312792
相关产品推荐
相关产品推荐

