Basically I need to take two arrays, merge them with unique values and sum one of columns. It makes more sense when written out below:
$a = [
['ID' => 1, 'Count' => 2],
];
$b = [
['ID' => 1, 'Count' => 4],
['ID' => 2, 'Count' => 3]
];
and I need the final product to be:
$a_plus_b = [
['ID' => 1, 'Count' => 6],
['ID' => 2, 'Count' => 3]
];
I have been playing with different variations of array_merge() and array_unique(), but I can’t find an efficient way to do what I need. I know I can always do nested loops, but I was hoping for something easier. Any ideas?
This should do the trick
Note: This solution requires PHP
>= 5.3. There is a PHP < 5.3 solution below.Output
Note the array keys above are
IDvalues. The array values areCountvalues.If you’re running PHP
< 5.2you won’t be able to use the inline closure witharray_fill. You have to define it as a separate function.From here, converting the output to your desired format is a trivial task.