合并数组时计算相同键值对的总和第一对 - php
I have 2 different arrays:
Array 1:
array(5) {
[0]=>
array(2) {
["all_totals"]=>
string(1) "3"
["month_name"]=>
string(3) "Jul"
}
[1]=>
array(2) {
["all_totals"]=>
string(2) "20"
["month_name"]=>
string(3) "Aug"
}
[2]=>
array(2) {
["all_totals"]=>
string(2) "10"
["month_name"]=>
string(3) "Sep"
}
[3]=>
array(2) {
["all_totals"]=>
string(2) "14"
["month_name"]=>
string(3) "Oct"
}
[4]=>
array(2) {
["all_totals"]=>
string(3) "102"
["month_name"]=>
string(3) "Nov"
}
}
Array 2:
array(2) {
[0]=>
array(2) {
["all_totals"]=>
string(1) "9"
["month_name"]=>
string(3) "Oct"
}
[1]=>
array(2) {
["all_totals"]=>
string(2) "30"
["month_name"]=>
string(3) "Nov"
}
}
For joining them and having only one foreach loop, I merged them:
$result = array_merge($array1, $array2);
foreach($result as $item){
//my actions here
}
But how you notice I have same key=>value pairs in both arrays. The only difference is ["all_totals"]
value. For example,
["all_totals"]=>"14", ["month_name"]=> "Oct"
and ["all_totals"]=> "9", ["month_name"]=> "Oct"
When merging I want to check whether there are such key-value pairs and join them by having one such element but sum ["all_totals"] values so that I won't lose any data. So in final result I will have one such element:
["all_totals"]=>"23", ["month_name"]=> "Oct"
Any ideas?
我有2个不同的数组: p>
数组1: p>
数组2: strong> p>
为了加入它们并只有一个foreach循环,我将它们合并: p>
但是你注意到我在两个数组中都有相同的key =>值对。 唯一的区别是 合并时我想检查是否有这样的键值对并通过一个这样的元素加入它们但是sum [“all_totals”]的值使得 我不会丢失任何数据。 因此,在最终结果中,我将有一个这样的元素: p>
任何想法? p>
div>
array(5){
[0] =>
array(2){
[“all_totals”] =>
string (1)“3”
[“month_name”] =>
string(3)“Jul”
}
[1] =>
array(2){
[“all_totals”] =>
string(2)“20”
[“month_name”] =>
string(3)“Aug”
}
[2] =>
array(2){\ n [“all_totals”] =>
string(2)“10”
[“month_name”] =>
string(3)“Sep”
}
[3] =>
array(2){
[“all_totals”] =>
string(2)“14”
[“month_name”] =>
string(3)“Oct”
}
[4 ] =>
array(2){
[“all_totals”] =>
string(3)“102”
[“month_name”] =>
string(3)“Nov”\ n}
}
code> pre>
array(2) {
[0] =>
array(2){
[“all_totals”] =>
string(1)“9”
[“month_name”] =>
string(3 )“Oct”
}
[1] =>
array(2){
[“all_totals”] =&g t;
string(2)“30”
[“month_name”] =>
string(3)“Nov”
}
}
code> pre>
$ result = array_merge($ array1,$ array2);
foreach($ result as $ item){
//我在这里的动作
}
code> pre>
[“all_totals”] code>值。 例如,
p>
[“all_totals”] =>“14”,[“month_name”] => “Oct” code>
和
[“all_totals”] => “9”,[“month_name”] => “Oct” code> p>
[“all_totals”] =>“23”,[“month_name”] => “十月” code> p>
What about this way to rome:
$coll=array();
foreach(array($arr,$arr2) as $array){
foreach($array as $a){
if(!isset($coll[$a['month_name']])){
$coll[$a['month_name']]=$a;
} else {
$coll[$a['month_name']]['all_totals'] += $a['all_totals'];
}
}
}
ksort($coll);
print_r(array_values($coll));