laravel collection groupBy() / 包含空结果



对于图表API,我需要提供每天的注册用户数。

//fetch all created_at dates of users from the last week
$signUpsLastWeek = User::whereDate('created_at', '>=', now()->subDays(7))->select('created_at')->get();
//group them now by date now, using collection operations
dd($signUpsLastWeek->groupBy(function($item) {
return $item->created_at->format('m.d');
}));
//now manipulate the collection a bit, so we get the date with the amount of new registered users
$signUpsLastWeek->mapWithKeys(function ($userGroup, $key) {
return [$key => $userGroup->count()];
})

返回:

IlluminateDatabaseEloquentCollection {#774 ▼
#items: array:1 [▼
"01.19" => 4
]
}

这工作正常,留下一个问题。

在上面的示例代码中,其他日期有 0 个新注册,这意味着集合应如下所示:

IlluminateDatabaseEloquentCollection {#774 ▼
#items: array:1 [▼
"01.25" => 0,
"01.24" => 0,
"01.23" => 0,
"01.22" => 0,
"01.20" => 0,
"01.19" => 4,
...,
]
}

知道如何也包括 0 金额吗?

我认为您可以使用CarbonPeriod来创建日历并为每个日期设置默认计数 0。

然后重置用户计数中的值:

$start_date = explode(' ', User::whereDate('created_at', '>=', now()->subDays(7))->min('created_at'))[0];
$end_date = CarbonCarbon::now()->format('Y-m-d');
$period = CarbonCarbonPeriod::create($start_date, $end_date);
$all_dates = [];
foreach ($period as $date) {
$all_dates = array_merge($all_dates, [$date->format('m.d') => 0]);
}
$all_dates = array_reverse($all_dates);
collect($all_dates)->mapWithKeys(function($v, $date) use ($signUpsLastWeek) {
if (in_array($date, array_keys($signUpsLastWeek))) {
return [$date => $signUpsLastWeek[$date]->count()];
} else {
return [$date => 0];
}
})->all();

相关内容

  • 没有找到相关文章

最新更新