2

I have two associative arrays and they are very similar to each other (But not the same) they are both separate arrays and I want to merge them together while maintaining both the arrays this can be done by:

  • Making sure the values ADD if the keys already exist (I.e both the arrays contain the key 'dragon' and maybe the value is '30' on the first array and '26' on the second i want it to give me '56'
  • If these keys don't exist in the first array, just merge it normally.

I've tried using $tagItems = array_count_values($tagItems, $tagItems2); but this just gives me null when i try to json encode and echo it out.

I've also tried using $tagItems = array_merge($tagItems, $tagItems2); this adds the new keys but doesn't merge the duplicate keys values (just keeps merged array values).

The arrays in JSON format look something like this, one array is called $tagItems, the other is called $tagItems2

{
   "game1": 22,
   "game2": 20,
   "game3": 16,
}
{
   "game1": 22,
   "game2": 20,
   "game3": 16,
   "game4": 12,
}

What will allow me to do this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
ConorReidd
  • 276
  • 5
  • 25

2 Answers2

6

At its shortest form where you want to merge $b into $a:

foreach ($b as $key => $value) {
    $a[$key] += $value;
}

Example

However, it's best that you check if the array key exists before you write to it:

if (!array_key_exists($key, $a)) {
    $a[$key] = 0;
}
$a[$key] += $value;
scrowler
  • 24,273
  • 9
  • 60
  • 92
  • @nogad, i was writing my answer like this `foreach(){if(key_exists(){$tagItems[$ti2]=$val})}` with variables of course, so what makes my longer better than his shorter??? – xYuri Sep 28 '16 at 22:23
  • @RobbieAverill, i think the OP wants to add the new vals as well as summing the old vals too, so your first works perfectly – xYuri Sep 28 '16 at 22:25
  • @xYuri the second half of the answer works the same way, just without undefined index errors – scrowler Sep 28 '16 at 22:35
1

This method uses mapping and allows either array to have keys not present in the other array.

$merged = array_fill_keys(array_keys($a + $b), 0);
$sums = array_map(
    function($aVal, $bVal) { return $aVal + $bVal; },
    array_merge($merged, $a),
    array_merge($merged, $b)
);
$merged = array_combine(array_keys($merged), $sums);
BrokenBinary
  • 7,731
  • 3
  • 43
  • 54