修改 Ismael Ansari 帖子,
$users = User::select('id', 'created_at')
->get()
->groupBy(function ($date) {
return Carbon::parse($date->created_at)->format('m');
});
$usermcount = [];
$userArr = [];
foreach ($users as $key => $value) {
$usermcount[(int)$key] = count($value);
}
$month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for ($i = 1; $i <= 12; $i++) {
if (!empty($usermcount[$i])) {
$userArr[$i]['count'] = $usermcount[$i];
} else {
$userArr[$i]['count'] = 0;
}
$userArr[$i]['month'] = $month[$i - 1];
}
return response()->json(array_values($userArr));
输出:
[
{
"count": 1,
"month": "Jan"
},
{
"count": 0,
"month": "Feb"
},
{
"count": 0,
"month": "Mar"
},
{
"count": 0,
"month": "Apr"
},
{
"count": 0,
"month": "May"
},
{
"count": 0,
"month": "Jun"
},
{
"count": 0,
"month": "Jul"
},
{
"count": 0,
"month": "Aug"
},
{
"count": 0,
"month": "Sep"
},
{
"count": 0,
"month": "Oct"
},
{
"count": 0,
"month": "Nov"
},
{
"count": 0,
"month": "Dec"
}
]