'Fold laravel collection with id
$arr1 = [
[10 , 0, 1, 2, 3],
[12 , 0, 1, 2, 3]
]
$arr2 = [
[9 , 0, 1, 2, 3],
[11 , 0, 1, 2, 3]
]
$arr3 = [
[9 , 0, 1, 2, 3],
[11 , 0, 1, 2, 3]
]
$arr4 = [
[8 , 0, 1, 2, 3],
[3 , 0, 1, 2, 3]
]
$result = [
[3 , 0, 1, 2, 3],
[8 , 0, 1, 2, 3],
[9 , 0, 2, 4, 6],
[11 , 0, 2, 4, 6],
[12 , 0, 1, 2, 3]
]
The first element is the id that should be added to the element of one collection with others. The output should be all exclusive ids, and if the id of one collection is assumed to be the same as the id in the other collection, a proposal is made. How to get the result?
Solution 1:[1]
Is this what you're looking for?
$result = collect(array_merge($arr1, $arr2, $arr3, $arr4))
->groupBy(fn ($record) => $record[0])
->map
->reduce(function ($carry, $item) {
// Iterate over grouped records, summing all keys expect 0.
foreach($item as $k => $v) {
$carry[$k] = $k !== 0 ? $v + ($carry[$k] ?? 0) : $v;
}
return $carry;
}, [])->sort()->values()->toArray();
dd($result);
This first groups on ID and then combines the values of all non 0 keys and finally sorts it by ID and returns it as array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | naamhierzo |
