0

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?

aiddev
  • 1,409
  • 2
  • 24
  • 56
  • Possible duplicate of [PHP: merge two arrays while keeping keys instead of reindexing?](http://stackoverflow.com/questions/3292044/php-merge-two-arrays-while-keeping-keys-instead-of-reindexing) – Masivuye Cokile Nov 16 '16 at 15:26
  • my question is different from the one you linked @MasivuyeCokile – aiddev Nov 16 '16 at 15:31

1 Answers1

1

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));
JustOnUnderMillions
  • 3,741
  • 9
  • 12
  • Thanks, I just removed ksort() as I was already ordered them in my sql query. Many thanks @JustOnUnderMillions – aiddev Nov 16 '16 at 15:55