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

Laravel中实现多集合对应位置元素求和的需求

Laravel 多集合对应位置元素求和

针对你需要将多个Laravel集合对应位置元素求和的需求,这里提供两种实用实现方式:

方式一:固定数量集合直接处理

如果集合数量是确定的,可以直接使用zip方法将对应位置元素打包,再通过map求和:

$collection1 = collect([1, 2, 3]);
$collection2 = collect([4, 8, 1]);
$collection3 = collect([5, 7, 1]);

$summedCollection = $collection1->zip($collection2, $collection3)
    ->map(fn($items) => collect($items)->sum());

// 输出结果:collect([10, 17, 5])

zip方法会把多个集合相同索引位置的元素组合成子集合,随后map遍历每个子集合并计算总和。

方式二:动态数量集合通用处理

如果集合数量不固定,可先将所有集合存入数组,转置后再逐组求和:

$collections = [
    collect([1, 2, 3]),
    collect([4, 8, 1]),
    collect([5, 7, 1]),
];

$summedCollection = collect($collections)
    ->map(fn($collection) => $collection->toArray())
    ->transpose()
    ->map(fn($items) => array_sum($items));

// 输出结果:collect([10, 17, 5])

步骤说明:

  • 先将每个集合转为普通数组
  • 使用transpose方法将数组转置(行变列,列变行)
  • 最后对转置后的每个子数组求和

内容的提问来源于stack exchange,提问作者ludenparis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:09:22