如何对Laravel Collection内子数组的指定字段进行求和归约
Solution
To get the aggregated sums of satisfactory, unsatisfactory, and total across all items in your Laravel Collection, you can use the built-in sum() method for each key, then wrap the results into a new Collection. Here's a straightforward approach:
Code Example
Assuming your original Collection is stored in $surveyResponses:
$summary = collect([ 'satisfactory' => $surveyResponses->sum('satisfactory'), 'unsatisfactory' => $surveyResponses->sum('unsatisfactory'), 'total' => $surveyResponses->sum('total'), ]);
How It Works
$surveyResponses->sum('satisfactory'): This calculates the total of allsatisfactoryvalues across every item in the Collection.- We repeat this pattern for
unsatisfactoryandtotal, then collect these three sums into a new Collection that matches your desired structure perfectly.
Alternative Single-Pass Approach
If you prefer to iterate through the Collection only once (though the sum() method is more readable), you can use reduce() to accumulate the totals step-by-step:
$summary = $surveyResponses->reduce(function ($accumulator, $item) { $accumulator['satisfactory'] += $item['satisfactory']; $accumulator['unsatisfactory'] += $item['unsatisfactory']; $accumulator['total'] += $item['total']; return $accumulator; }, [ 'satisfactory' => 0, 'unsatisfactory' => 0, 'total' => 0, ]); // Convert the array result to a Collection if needed $summaryCollection = collect($summary);
Either method will produce the exact Collection structure you want:
Collection {#319 ▼ #items: array:3 [▼ "satisfactory" => 8 "unsatisfactory" => 2 "total" => 10 ] }
内容的提问来源于stack exchange,提问作者Luis felipe De jesus Munoz
相关产品推荐
相关产品推荐

