实际上我有数组值
Array ( [0] => Array ( [total_amount] => 4080 [supplier] => 81 )
[249] => Array ( [total_amount] => 8400 [supplier] => 81 )
[466] => Array ( [total_amount] => 20340 [supplier] => 82 )
[519] => Array ( [total_amount] => 2100 [supplier] => 83 )
[1078] => Array ( [total_amount] => 40199 [supplier] => 83 )
)
我希望输出(每个供应商的总金额总和)
Array ( [81] => 12480
[82] => 20340
[83] => 42299
)
我尝试了以下代码
$new = array_filter($array, function ($var) { return ($var['supplier'] += $var['total_amount']); });
请帮我解决我的问题。
答案 0 :(得分:0)
简单方法:
$result = [];
foreach ($arr as $a) { // $arr is your initial array
(isset($result[$a['supplier']]))?
$result[$a['supplier']] += $a['total_amount']
: $result[$a['supplier']] = $a['total_amount'];
}
print_r($result);
输出:
Array
(
[81] => 12480
[82] => 20340
[83] => 42299
)
答案 1 :(得分:0)
array_filter
并非设计用于此类任务,请使用array_walk
像:
$new = [];
array_walk($array, function ($var) use (&$new) {
if(isset($new[$var['supplier']])){
$new[$var['supplier']] += $var['total_amount'];
}else{
$new[$var['supplier']] = $var['total_amount'];
}
});