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 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。