Collection 如何快速合并两组数据

一. 使用场景

数据来源不同但又需要将他们相加的情况

```php
$arr = [
    [
        "time" => "2019-01"
        "total_price" => 20
        "name" => 1
    ],
    [
        "time" => "2019-01"
        "total_price" => 40
        "name" => 2
    ],
    [
        "time" => "2019-02"
        "total_price" => 30
        "name" => 1
    ],
    [
        "time" => "2019-02"
        "total_price" => 10
        "name" => 2
    ]
]

$arr_mix = [
    [
        "time" => "2019-01"
        "total_price" => 10
        "name" => 1
    ],
    [
        "time" => "2019-02"
        "total_price" => 20
        "name" => 2
    ]
]

二. 目的将相同的月份name相同的total_price相加

1.转换为 collection

```php

$col = collect($arr);

$col_mix = collect($arr_mix);

2.设置数据的id(唯一,可以方便取得这条数据的方式,方法)

```php
 $col = $col->keyBy(function ($item) {
    return $item['time'] . '@' . $item['name'];
 });

3.使用collection 的reduce 方法进行合并

```php
$reduceTotalPrice = function (Collection $total, $item) {
    $identify = $item['time'] . '@' . $item['name'];
    if ($total->has($identify)) {
        $temp = $total->get($identify);
        data_set($temp, 'total_price', $temp['total_price'] + $item['total_price']);
    } else {
        $total->offsetSet($identify, $item);
    }
};

$col = $col_mix->reduce(function ($total, $item) use ($reduceTotalPrice) {
    $reduceTotalPrice($total, $item);
    return $total;
}, $colKey);

return $col->flatten();
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!