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 协议》,转载必须注明作者和本文链接
xiawu 的个人博客
关于 LearnKu
推荐文章: