I have a two-dimensional array like this:like this:
[
['city' => 'NewYork', 'cash' => 1000],
['city' => 'Philadelphia', 'cash' => 2300],
['city' => 'NewYork', 'cash' => 2000]
]
I'd like to sum the value cash
of rows which share the same city
value to form a result with the same 2d structure.
Desired result:
[
['city' => 'NewYork', 'cash' => 3000],
['city' => 'Philadelphia', 'cash' => 2300],
]
Try below code:
<?php
$arr = array(
array('city' => 'NewYork', 'cash' => '1000'),
array('city' => 'Philadelphia', 'cash' => '2300'),
array('city' => 'NewYork', 'cash' => '2000'),
);
$newarray = array();
foreach($arr as $ar)
{
foreach($ar as $k => $v)
{
if(array_key_exists($v, $newarray))
$newarray[$v]['cash'] = $newarray[$v]['cash'] + $ar['cash'];
else if($k == 'city')
$newarray[$v] = $ar;
}
}
print_r($newarray);
Output:
Array
(
[NewYork] => Array
(
[city] => NewYork
[cash] => 3000
)
[Philadelphia] => Array
(
[city] => Philadelphia
[cash] => 2300
)
)
Demo:
http://3v4l.org/D8PME