I got a multidimensional array like this:
Totalarray
(
[0] => Array
(
[city] => NewYork
[cash] => 1000
)
[1] => Array
Using any more than one loop (or looping function) to sum the values is inefficient.
Here is a method that uses temporary keys to build the result array and then reindexes the result array after the loop terminates.
Code: (Demo)
$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