Use function array_reduce()
to combine the items having the same 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()
);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…