gpt4 book ai didi

laravel - 如果键值相同,如何合并 Laravel 集合?或添加新的数据行

转载 作者:行者123 更新时间:2023-12-04 09:50:43 26 4
gpt4 key购买 nike

我有两个系列,比如..

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

我需要根据日期排列数据。

最佳答案

假设集合是这样的;

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 - 如果键值相同,如何合并 Laravel 集合?或添加新的数据行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62018789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com