我有一个PHP数组,我想对每个重复元素的所有值求和,然后只返回一个总和为最后的数组...这是示例数组
[0] => Array
(
[purchase_amount] => 5000.00
[listing_price] => 5000.00
[home_warranty_cost] => 10.00
[emd] => 100.00
[fee] => 10.00
)
[1] => Array
(
[purchase_amount] => 0.00
[listing_price] => 0.00
[home_warranty_cost] => 10.00
[emd] => 100.00
[fee] => 10.00
)
[2] => Array
(
[purchase_amount] => 15000.00
[listing_price] => 15000.00
[home_warranty_cost] => 10.00
[emd] => 100.00
[fee] => 10.00
)
最后,我只想...
(
[purchase_amount] => 20000.00
[listing_price] => 20000.00
[home_warranty_cost] => 30.00
[earnest_money_amount] => 300.00
[tc_fee] => 30.00
)
是否有一个简单的函数可以执行此操作,还是需要编写一个for循环?
答案 0 :(得分:3)
这很适合array_reduce
[doc],无论您的键名如何,它都可以工作。
array_reduce
的回调函数适用于输入数组的每个元素,并采用累加器$carry
和当前元素$item
。如果累加器为空,则这是归约过程中的第一个元素,因此我们可以直接进行赋值。否则,请循环遍历当前元素的条目,并将值添加到累加器。
array_reduce($data, function ($carry, $item) {
if (!$carry) {
$carry = $item;
}
else {
foreach ($item as $k => $v) {
$carry[$k] += $v;
}
}
return $carry;
});
结果:
Array
(
[purchase_amount] => 20000
[listing_price] => 20000
[home_warranty_cost] => 30
[emd] => 300
[fee] => 30
)
答案 1 :(得分:1)
我会做这样的事情。键上仍然有一个循环,但这对于每次都不列出所有字段是必要的...
$sums = array_reduce($data, function ($carry, $item) {
foreach ($item as $key => $value)
{
$carry[$key] = array_key_exists($key, $carry) ? $carry[$key] + $item[$key] : 0;
}
return $carry;
}, []);
Working example在这里。