3 回答

TA贡献1856条经验 获得超5个赞
使用isset将避免未定义的偏移错误:
$new_data = [];
foreach($data as $k => $v){
if (!isset($new_data[$v['code']]['ttl'])){
$new_data[$v['code']]['ttl'] = 0;
}
$new_data[$v['code']]['ttl'] += $v['count'];
}
print_r($new_data);

TA贡献1848条经验 获得超2个赞
假设您希望 to 中的键$new_data是唯一的代码,并且值是一个数组,ttl其键的值是该特定代码的计数总和:
$new_data = [];
foreach($data as $v){
if (!array_key_exists($v['code'], $new_data)) {
$new_data[$v['code']]['ttl'] = $v['count'];
} else {
$new_data[$v['code']]['ttl'] += $v['count'];
}
}

TA贡献1777条经验 获得超10个赞
我认为这就是您想要的输出:
Array
(
[2] => Array
(
[ttl] => 8
)
[3] => Array
(
[ttl] => 9
)
[11] => Array
(
[ttl] => 6
)
[17] => Array
(
[ttl] => 14
)
)
如果是这样,您可以对代码进行少量修改,如下所示:
$new_data = [];
foreach ($data as $d) {
if (isset($new_data[$d['code']]['ttl'])) {
$new_data[$d['code']]['ttl'] += $d['count'];
} else {
$new_data[$d['code']]['ttl'] = $d['count'];
}
}
- 3 回答
- 0 关注
- 102 浏览
添加回答
举报