按日期Laravel数据表求和



我在Laravel 8,中对数据表进行分组时遇到问题

这是数据,

Table: cash_in
Date        Code    Amount
2020-12-01  0001    100
2020-12-01  0001    200
2020-12-01  0002    300
2020-12-01  0002    400
2020-12-02  0001    500
2020-12-02  0002    600
2020-12-02  0002    700

我想根据日期对代码0001和代码0002进行分组并求和。

Date        0001    0002
2020-12-01  300     700
2020-12-02  500     1300

请帮我提出这个解决方案。提前谢谢。

尝试这个

$data = [
[
"Date" => "2020-12-01",
"Code" => "0001",
"Amount" => "100",
],
[
"Date" => "2020-12-01",
"Code" => "0001",
"Amount" => "200",
],
[
"Date" => "2020-12-01",
"Code" => "0002",
"Amount" => "300",
],
[
"Date" => "2020-12-01",
"Code" => "0002",
"Amount" => "400",
],
[
"Date" => "2020-12-02",
"Code" => "0001",
"Amount" => "500",
],
[
"Date" => "2020-12-02",
"Code" => "0002",
"Amount" => "500",
],
[
"Date" => "2020-12-02",
"Code" => "0002",
"Amount" => "700",
]
];
$data = collect($data);
$newData = $data->groupBy('Date')->map(function ($item, $key) {
return [
"date" => $key,
"total" => $item->sum('Amount'),
"code"=>$item[0]['Code'],
];
})->values();
return $newData;

相关内容

  • 没有找到相关文章

最新更新