如果键值相同,如何合并 laravel 集合?或添加新的数据行
Posted
技术标签:
【中文标题】如果键值相同,如何合并 laravel 集合?或添加新的数据行【英文标题】:How to merge laravel collection if key values are same? or add new row of data 【发布时间】:2020-09-13 01:23:52 【问题描述】:我有两个系列,比如..
date sum_total count_total
2020-05-10 10 5
2020-05-11 11 6
2020-05-13 5 7
第二次收集
date1 sum_total1 count_total2
2020-05-10 1 5
2020-05-12 2 4
2020-05-13 0 7
我需要像...这样的输出
date sum_total count_total
2020-05-10 11 10
2020-05-11 11 6
2020-05-12 2 4
2020-05-13 5 14
我需要按日期排列数据。
【问题讨论】:
【参考方案1】:假设集合是这样的;
public function index()
$first = collect([
[
'date' => '2020-05-10',
'sum_total' => 10,
'count_total' => 5,
],
[
'date' => '2020-05-11',
'sum_total' => 11,
'count_total' => 6,
],
[
'date' => '2020-05-13',
'sum_total' => 5,
'count_total' => 7,
]
]);
$second = collect([
[
'date' => '2020-05-10',
'sum_total' => 1,
'count_total' => 5,
],
[
'date' => '2020-05-12',
'sum_total' => 2,
'count_total' => 4,
],
[
'date' => '2020-05-13',
'sum_total' => 0,
'count_total' => 7,
]
]);
return $first->merge($second)
->groupBy('date')
->map(function ($sub)
return [
'date' => $sub->first()['date'],
'sum_total' => $sub->sum('sum_total'),
'count_total' => $sub->sum('count_total'),
];
)
->sortBy('date')
->values();
打印出来;
[
"date": "2020-05-10",
"sum_total": 11,
"count_total": 10
,
"date": "2020-05-11",
"sum_total": 11,
"count_total": 6
,
"date": "2020-05-12",
"sum_total": 2,
"count_total": 4
,
"date": "2020-05-13",
"sum_total": 5,
"count_total": 14
]
【讨论】:
以上是关于如果键值相同,如何合并 laravel 集合?或添加新的数据行的主要内容,如果未能解决你的问题,请参考以下文章