题目描述如何对二维数组内相同的key的值相加题目来源及自己的思路把一个二维数组 相同的hid的sum相加自己做的是 $array=[]; foreach ($arr as $k=>$v){
$array[$v['hid']][]=$v;
}
$list=[]; foreach ($array as $k=>$v){ foreach ($v as $k1=>$v1){
$list[$k]+=$v1['sum'];
}
}
dump($list); 出来 array(4) {[2] => int(6) [3] => int(7)[5] => int(6) [4] => int(5)相关代码// 请把代码文本粘贴到下方(请勿用图片代替代码)就是把下面的转为 $list=[6,7,6,5];$arr=[
['id'=>1,'hid'=>2,'sum'=>1],
['id'=>2,'hid'=>2,'sum'=>2],
['id'=>3,'hid'=>2,'sum'=>3],
['id'=>4,'hid'=>3,'sum'=>1],
['id'=>5,'hid'=>3,'sum'=>2],
['id'=>6,'hid'=>3,'sum'=>4],
['id'=>7,'hid'=>5,'sum'=>2],
['id'=>8,'hid'=>5,'sum'=>4],
['id'=>9,'hid'=>4,'sum'=>5]
];}你期待的结果是什么?实际看到的错误信息又是什么?如何优化我的代码。我写的循环太多了。我想要的结果就是 相同的hid的sum相加
1 回答
FFIVE
TA贡献1797条经验 获得超6个赞
<?php$arr = [ ['id' => 1, 'hid' => 2, 'sum' => 1], ['id' => 2, 'hid' => 2, 'sum' => 2], ['id' => 3, 'hid' => 2, 'sum' => 3], ['id' => 4, 'hid' => 3, 'sum' => 1], ['id' => 5, 'hid' => 3, 'sum' => 2], ['id' => 6, 'hid' => 3, 'sum' => 4], ['id' => 7, 'hid' => 5, 'sum' => 2], ['id' => 8, 'hid' => 5, 'sum' => 4], ['id' => 9, 'hid' => 4, 'sum' => 5] ]; $result = [];foreach ($arr as $item) { // 降低了对低版本的照顾 isset($result[$item['hid']]) || $result[$item['hid']] = 0; $result[$item['hid']] += $item['sum']; } $result = array_values($result); var_dump($result);
- 1 回答
- 0 关注
- 1824 浏览
添加回答
举报
0/150
提交
取消