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.