I'm generating the following array in json format
[
{
"country": "China",
"amount": "1"
},
{
"country": "India",
"amount": "5"
},
{
"country": "India",
"amount": "317"
},
{
"country": "India",
"amount": "8"
},
{
"country": "India",
"amount": "2"
},
{
"country": "United States",
"amount": "213"
},
{
"country": "Iceland",
"amount": "263"
}
]
I've tried merging them with the following code
$newData = array();
$result = array_reduce(
$data,
function($newData, $value) {
$key = $value['country'];
if (!isset($newData[$key])) {
$newData[$key] = $value;
} else {
$newData[$key]['amount'] += $value['amount'];
}
return $newData;
},
$newData
);
my desired output is
[
{
"country": "China",
"amount": "1"
},
{
"country": "India",
"amount": "332"
},
{
"country": "United States",
"amount": "213"
},
{
"country": "Iceland",
"amount": "263"
}
]
As you can see the array is merged with all the country values grouped and the amount values added accordingly.
Use a simple foreach
loop rather than array_reduce
.
$newData = array();
foreach ($data as $e) {
if (isset($newData[$e['country']])) {
$newData[$e['country']]['amount'] += $e['amount'];
} else {
$newData[$e['country']] = $e;
}
}
$newData = array_values($newData);
Try this:
$newData = array();
foreach($oldData as $oldEntry){
foreach($newData as $newEntry){
if($oldEntry['country'] == $newEntry['country'])
$newEntry['country'] += $oldEntry['country'];
break;
}
$newData[] = array('country' => $oldEntry['country'], 'amount' => $oldEntry['amount'];
}