I have a collection like
$collection = collect([
[
["studentId" => 3, "marks" => 10],
["studentId" => 7, "marks" => 15]
],
[
["studentId" => 3, "marks" => 20],
["studentId" => 7, "marks" => 15]
],
[
["studentId" => 3, "marks" => 10],
["studentId" => 7, "marks" => 20]
],
]);
I want to sum up marks for specific studentId and map the results like
[
["studentId" => 3, "marks" => 40],
["studentId" => 7, "marks" => 50],
]
Thanks
This is untested but you can probably do something like...
What this does is...
1. Flatten the array
First we flatten the collection by 1 depth using the
flattenmethod. Resulting structure...2. Group values by
Next we group all the values by the studentId using the
groupBymethod. Result...3. Sum the marks
Now we calculate the groups of marks with the
transformmethod. Result...4. Reset keys (optional)
You'll notice in the last result that the top level array keys are the same as the studentId values this is left over from the groupBy method. We can reset these with the
valuesmethod. Result...