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"}
]
@Cloud I have made function for your requirement and Thanks @M. I. for look into this sum section.
$array = array(
array("ID" => "126871","total"=>"200.00","currency"=>"USD","name"=>"John"),
array("ID" => "126872","total"=>"2000.00","currency"=>"Euro","name"=>"John"),
array("ID" => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John"),
array("ID" => "126872","total"=>"500.00","currency"=>"USD","name"=>"John"),
array("ID" => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John"),
);
echo "<pre>";
print_r($array);
function unique_multidim_array($array, $key,$key1,$addedKey) {
$temp_array = array();
$i = 0;
$key_array = array();
$key1_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array) && !in_array($val[$key1], $key1_array)) {
$key_array[$i] = $val[$key];
$key1_array[$i] = $val[$key1];
$temp_array[$i] = $val;
}else{
$pkey = array_search($val[$key],$key_array);
$pkey1 = array_search($val[$key1],$key1_array);
if($pkey==$pkey1){
$temp_array[$pkey][$addedKey] += $val[$addedKey];
}else{
$key_array[$i] = $val[$key];
$key1_array[$i] = $val[$key1];
$temp_array[$i] = $val;
}
// die;
}
$i++;
}
return $temp_array;
}
$nArray = unique_multidim_array($array,"ID","currency","total");
// die;
print_r($nArray);
die;