ConorReidd ConorReidd - 2 months ago 31
PHP Question

PHP - Merge two associative arrays (add values if key exists)

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?

Answer

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;
Comments