如何对重复数据的数组值求和 [英] How to sum array value of duplicate data
本文介绍了如何对重复数据的数组值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,其某些值与ID
相同,如下所示.
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"},
]
如果ID
值重复,则求和同一currency
的总和.对于相同ID
的不同currency
,无需求和total
.
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
.
这就是我想要的.
[
{"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 am stuck with the above problem. I already tried as much as I can. But I got the wrong result. I'm very appreciative for any advice.
推荐答案
@Cloud我已根据您的要求提供了功能,感谢@M. I.对此总和部分进行了研究.
@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;
这篇关于如何对重复数据的数组值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文