I have 10 (3 used for the example below) collections I need to merge together by key but need to sum the values. My collections look like this:
[
'key1' => ['value1' => 5, 'value2' => 3, 'value3' => 0],
'key2' => ['value1' => 1, 'value2' => 6, 'value3' => 2],
'key3' => ['value1' => 0, 'value2' => 0, 'value3' => 1],
]
[
'key1' => ['value1' => 3, 'value2' => 1, 'value3' => 7],
'key2' => ['value1' => 1, 'value2' => 3, 'value3' => 2],
'key3' => ['value1' => 1, 'value2' => 6, 'value3' => 1],
]
[
'key1' => ['value1' => 2, 'value2' => 3, 'value3' => 9],
'key2' => ['value1' => 3, 'value2' => 8, 'value3' => 3],
'key3' => ['value1' => 1, 'value2' => 0, 'value3' => 6],
]
I'd like to get one collection where the result looks like this:
[
'key1' => ['value1' => 10, 'value2' => 7, 'value3' => 16],
'key2' => ['value1' => 5, 'value2' => 17, 'value3' => 7],
'key3' => ['value1' => 2, 'value2' => 6, 'value3' => 8],
]
Is there a built in Laravel Collection method I'm missing or what is the best way to achieve this?
edit: (more info) The values are always numeric. There are no string values in any of the collections.
edit2: Some people are asking what I've tried. I've tried this which works:
$merged = [];
foreach ($seeds as $seed) {
foreach ($seed as $location => $values) {
foreach ($values as $key => $value) {
$merged[$location][$key] = $value + ($merged[$location][$key] ?? 0);
}
}
}
I was just wondering if there was a more succinct way of achieving the same thing instead of using 3 foreach loops.