我正在学习JSON,我想显示一个自定义输出。日期是一样的,必须加在一起。
我的数据库表的数据如下:
id no_id type created_at
------------------------------------------------
1 1 post 2023-10-11T17:13:19.000000Z
2 85 post 2023-10-11T17:13:19.000000Z
3 23 post 2023-10-12T17:24:33.000000Z
4 40 post 2023-10-12T17:24:33.000000Z
5 87 product 2023-10-12T17:24:33.000000Z
范例:
2023-10-11 => 2
2023-10-12 => 3
我的Laravel控制器文件如下:
class StatController extends Controller {
public function index() {
$stats = Stat::groupBy(DB::raw('DATE(created_at)'))->get()->toArray();
return array_reverse($stats);
}
}
控制器代码的输出如下所示(json):
[
{
"id": 2,
"no_id": 85,
"type": "post",
"created_at": "2023-10-11T17:13:19.000000Z"
},
{
"id": 5,
"no_id": 87,
"type": "product",
"created_at": "2023-10-12T17:24:33.000000Z"
}
]
但我想显示JSON输出如下:
[
{
"date": "2023-10-11",
"totalViews": "2"
},
{
"date": "2023-10-12",
"totalViews": "3"
}
]
1条答案
按热度按时间zf9nrax11#
您可以尝试groupBy
created_at
并像这样计算每个组: