0

I would like to know what is the best way to merge some arrays with a same value.

My output :

array (size=16)
  'totalAttemps' => int 4
  'totalSuccess' => int 4
  'totalFailed' => int 0
  'ituCount' => int 0
  'pddSuc' => int 11543
  'pddFailed' => int 0
  'ituCount34' => int 0
  'FAS10' => int 4
  'FAS20' => int 4
  'FAS40' => int 4
  'FAS60' => int 4
  'region' => string 'TEST'
  'oneOne' => int 24
  'sixSix' => int 48
  'thirtySix' => int 120
  'sixtySixty' => int 240
array (size=16)
  'totalAttemps' => int 1
  'totalSuccess' => int 1
  'totalFailed' => int 0
  'ituCount' => int 0
  'pddSuc' => int 5829
  'pddFailed' => int 0
  'ituCount34' => int 0
  'FAS10' => int 1
  'FAS20' => int 1
  'FAS40' => int 1
  'FAS60' => int 1
  'region' => string 'TEST'
  'oneOne' => int 6
  'sixSix' => int 12
  'thirtySix' => int 30
  'sixtySixty' => int 60

I would like :

array (size=16)
  'totalAttemps' => int 5
  'totalSuccess' => int 5
  'totalFailed' => int 0
  'ituCount' => int 0
  'pddSuc' => int 17372
  'pddFailed' => int 0
  'ituCount34' => int 0
  'FAS10' => int 5
  'FAS20' => int 5
  'FAS40' => int 5
  'FAS60' => int 5
  'region' => string 'TEST'
  'oneOne' => int 30
  'sixSix' => int 60
  'thirtySix' => int 150
  'sixtySixty' => int 300

I can use += to count but I would count only for the same region because there are a lot of regions. Thank you.

Vincent Moulene
  • 1,193
  • 2
  • 15
  • 28

1 Answers1

0

A more manual version than Carlos's, but very straightforward:

$arr1 = YOUR_ARRAY_1;
$arr2 = YOUR_ARRAY_2;
$merged = $arr1;

foreach($arr2 as $key => $val) {
    if(array_key_exists($key, $merged)) {
        $merged[$key] += $val;
    } else {
        $merged[$key] = $val;
    }
}

This starts with $arr1, and goes through each element of $arr2. If the key exists in $arr1, then add $arr2's value. If not, then create a new element of the array.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94