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:
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?
At its shortest form where you want to merge $b
into $a
:
foreach ($b as $key => $value) {
$a[$key] += $value;
}
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;