You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对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 all satisfactory values across every item in the Collection.
  • We repeat this pattern for unsatisfactory and total, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:01:37