Cloud Cloud - 3 months ago 14
PHP Question

How to sum array value of duplicate data

I have an array with some of same

ID
value as shown in below.

[
{"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"},
]


If the
ID
value is duplicate, sum the total value of the same
currency
. For the different
currency
of same
ID
, no need to sum
total
.

Here is what I want.

[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":"4000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"}
]


I have stuck with above problem. I already tried as much as I can. But I got the wrong result. I'm very appreciate for any advice.

Answer

@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;
Comments