3 回答
TA贡献1806条经验 获得超8个赞
使用功能array_reduce()组合具有相同功能的项目city:
$input = array(
array('city' => 'NewYork', 'cash' => '1000'),
array('city' => 'Philadelphia', 'cash' => '2300'),
array('city' => 'NewYork', 'cash' => '2000'),
);
$output = array_reduce(
// Process the input list
$input,
// Add each $item from $input to $carry (partial results)
function (array $carry, array $item) {
$city = $item['city'];
// Check if this city already exists in the partial results list
if (array_key_exists($city, $carry)) {
// Update the existing item
$carry[$city]['cash'] += $item['cash'];
} else {
// Create a new item, index by city
$carry[$city] = $item;
}
// Always return the updated partial result
return $carry;
},
// Start with an empty list
array()
);
TA贡献1796条经验 获得超10个赞
使用不止一个循环(或循环功能)来求和这些值是无效的。
这是一种使用临时键构建结果数组,然后在循环终止后重新索引结果数组的方法。
代码:(演示)
$array=[
['city' => 'NewYork', 'cash' => '1000'],
['city' => 'Philadelphia', 'cash' => '2300'],
['city' => 'NewYork', 'cash' => '2000']
];
foreach($array as $a){
if(!isset($result[$a['city']])){
$result[$a['city']] = $a; // store temporary city-keyed result array (avoid Notices)
}else{
$result[$a['city']]['cash'] += $a['cash']; // add current value to previous value
}
}
var_export(array_values($result)); // remove temporary keys
- 3 回答
- 0 关注
- 577 浏览
添加回答
举报