小编典典

如何对重复数据的数组值求和

json

我有一些具有相同ID值的数组,如下所示。

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

如果ID值重复,则将相同的总和相加currency。对于currency相同的不同ID,无需求和total

这就是我想要的。

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

我陷入上述问题。我已经尽力了。但是我得到了错误的结果。我非常感谢任何建议。


阅读 432

收藏
2020-07-27

共1个答案

小编典典

@Cloud我已根据您的要求提供了功能,感谢@MI对此总和部分进行了研究。

$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;
2020-07-27