I have an array with some of same ID value as shown in below.
[
{\"ID\":\"126871\",\"total\":\"200.00\",\"currency\":\"USD\",\"name\":\"John
You will need to:
json_decode.ID & currency values and use that string as the temporary unique key.total values.json_encode().Code: (Demo)
$json='[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":"2000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"1000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"},
{"ID":"126872","total":"1000.00","currency":"Euro","name":"John"}
]';
$array=json_decode($json,true); // convert to array
foreach($array as $row){
if(!isset($result[$row['ID'].$row['currency']])){
$result[$row['ID'].$row['currency']]=$row; // on first occurrence, store the full row
}else{
$result[$row['ID'].$row['currency']]['total']+=$row['total']; // after first occurrence, add current total to stored total
}
}
$result=json_encode(array_values($result)); // reindex the array and convert to json
echo $result; // display
Output:
[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":4000,"currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"}
]