0

对于图表 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()];
})

回报:

Illuminate\Database\Eloquent\Collection {#774 ▼
  #items: array:1 [▼
    "01.19" => 4
  ]
}

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

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

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

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

4

1 回答 1

0

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

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

$start_date = explode(' ', User::whereDate('created_at', '>=', now()->subDays(7))->min('created_at'))[0];
$end_date = \Carbon\Carbon::now()->format('Y-m-d');
$period = \Carbon\CarbonPeriod::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();
于 2020-01-25T09:49:16.290 回答