dongli564510 2018-02-09 00:51
浏览 58

如何将集合折叠为一个并对特定键求和

I have following collection:

array:2 [▼
  0 => array:21 [▼
    "id" => 1
    "referrer" => "Kariane Muller DVM"
    "path" => null
    "tracking_code_id" => 30
    "sales" => 2
    "field_name" => "ssn"
    "income" => 4.0
    "fsId" => "1b5e4434-da5a-342e-9b87-df9791b1bcc1"
  ]
  2 => array:21 [▼
    "id" => 1
    "referrer" => "Kariane Muller DVM"
    "path" => null
    "tracking_code_id" => 30
    "sales" => 1
    "field_name" => "income"
    "income" => 1.0
    "fsId" => "1b5e4434-da5a-342e-9b87-df9791b1bcc1"
  ]

For visibility purposes I have converted it to array.

How can I collapse this collection into one collection, but I want to sum the income keys into one in final collection.

Other keys should be included as they are ?

  • 写回答

1条回答 默认 最新

  • doudao2407 2018-02-09 04:00
    关注

    I would start with reduce. If I am understanding correctly you basically want the original collection intact but the income to be summed and reflected in every item.

    $summedIncome = $collection->reduce(function ($carry, $item) {
        $income = $carry->has('income') ? ($item->income + $carry->income) : $item->income;
        $carry->push($item);
        $carry->each->income = $income;
        return $carry;
    }, collect([]));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用