I have the following array structure:
[0] => Array
(
[name] => Spinat boller
[amount] => 3
[category] => Bløddej og Boller
[unit_amount] => 15
)
[1] => Array
(
[name] => Bedste boller
[amount] => 15
[category] => Bløddej og Boller
[unit_amount] => 15
)
[2] => Array
(
[name] => Grov boller
[amount] => 15
[category] => Bløddej og Boller
[unit_amount] => 15
)
I have multiple of these arrays, and i would like to merge them on the AMOUNT KEY ONLY. That means if i have another array containing this:
[0] => Array
(
[name] => Spinat boller
[amount] => 2
[category] => Bløddej og Boller
[unit_amount] => 15
)
And i merge it, it would show this:
[0] => Array
(
[name] => Spinat boller
[amount] => 5
[category] => Bløddej og Boller
[unit_amount] => 15
)
Obviously i could traverse this manually, but i was hoping i could utilize the PHP Merge function somehow, but not sure how to go about it.
Thanks everyone!
* Edit 1 * If i just do the array_merge function, it simply appends it all together, so i go from:
[0] => Array
(
[name] => Spinat boller
[amount] => 3
[category] => Bløddej og Boller
[unit_amount] => 15
)
to:
[0] => Array
(
[name] => Spinat boller
[amount] => 3
[category] => Bløddej og Boller
[unit_amount] => 15
)
[0] => Array
(
[name] => Spinat boller
[amount] => 2
[category] => Bløddej og Boller
[unit_amount] => 15
)
but i want:
[0] => Array
(
[name] => Spinat boller
[amount] => 3
[category] => Bløddej og Boller
[unit_amount] => 15
)
[0] => Array ( [name] => Spinat boller [amount] => 5 [category] => Bløddej og Boller [unit_amount] => 15 )
Notice how the amount is now 5 (the other arrays had 2 and 3). Everything else is the same and matches, ONLY the amount gets added and incremented.
So I gave it some thought, to see if it's possible to do it in a single expression.
You have to combine quite a few functions, but the behaviour is the same as with manual iteration. The result of this functional approach looks like this:
$result = array_values(
array_merge(
...array_reverse(
array_map(function ($arr) {
return array_combine(
array_column($arr, 'name'),
array_values($arr)
);
}, [$arr1, $arr2, $arr3])
)
)
);
Though it can be done, I sticking with the iteration approach would be best for maintainability reasons:
$tmp = [];
foreach ($arrays as $arr) {
foreach ($arr as $elem) {
if (!isset($tmp[$elem['name']])) {
$tmp[$elem['name']] = $elem;
}
}
}
$result = array_values($tmp);