按日期进行分组
#统计七天内注册用户数量按天进行分组
$start_date = '2018-01-01';
$end_date = '2018-01-07';
$users = DB::table('users')->whereBetween('created_at',[$start_date ,$end_date])
->selectRaw('DATE(created_at) as date,COUNT(*) as num')
->groupBy('date')
->get();
#获取的用户分组数据
{
"date": "2018-01-01", #日期
"num": 199 #数量
},
{
"date": "2018-01-02",
"num": 298
},
{
"date": "2018-01-03",
"num": 399
},
...
#在进行图表统计的时候直接从数据库取得数据有些日期可能是没有的,就需要我们手动进行补全一些日期
#计算日期内天数
$stimestamp = strtotime($start_time);
$etimestamp = strtotime($end_time);
#计算日期段内有多少天
$days = ($etimestamp - $stimestamp) / 86400;
#保存每天日期
$date = array();
for($i = 0;$i < $days;$i++){
$date[] = date('Y-m-d', $stimestamp + (86400 * $i));
}
#循环补全日期
foreach ($date as $key => $val){
$data[$key] = [
'date' => $val,
'num' => 0
];
foreach ($user as $item => $value){
if($val == $value['date']){
$data[$key] = $value;
}
}
}
return $data;
按月份进行分组
#统计一年内注册用户数量按月份进行分组
$user = DB::table('users')->whereBetween('created_at',['2018-01-01','2018-12-31'])
->selectRaw('DATE_FORMAT(created_at,"%Y-%m") as date,COUNT(*) as num')
->groupBy('date')
->get();
#获取的用户分组数据
{
"date": "2018-01", #月份
"num": 1497 #数量
},
{
"date": "2018-02",
"num": 2354
},
{
"date": "2018-03",
"num": 4560
}
#在进行图表统计的时候直接从数据库取得的数据有的月份可能是没有的,不过月份比较少可直接写死,同样也需要补全
$year = date('Y',time());
#一年的月份
$months = [
0 => $year.'-01',
1 => $year.'-02',
2 => $year.'-03',
3 => $year.'-04',
4 => $year.'-05',
5 => $year.'-06',
6 => $year.'-07',
7 => $year.'-08',
8 => $year.'-09',
9 => $year.'-10',
10 => $year.'-11',
11 => $year.'-12'
];
#循环补全月份
foreach ($months as $key => $month){
$data[$key] = [
'date' => $month,
'num' => 0
];
foreach ($user as $k => $v){
if($month == $v['date']){
$data[$k] = $v;
}
}
}
return $data;