我有一个像这样的二维数组:像这样:
[
['city' => 'NewYork', 'cash' => 1000],
['city' => 'Philadelphia', 'cash' => 2300],
['city' => 'NewYork', 'cash' => 2000]
]
我想对值进行求和cash
共享相同的行city
值以形成具有相同二维结构的结果。
期望的结果:
[
['city' => 'NewYork', 'cash' => 3000],
['city' => 'Philadelphia', 'cash' => 2300],
]
使用功能array_reduce() http://php.net/manual/en/function.array-reduce.php合并具有相同的项目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()
);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)