最近接到一个需求:
1.要求做一些大屏数据展示,数据可视化,将用户的一些数据(例如评论次数、投诉次数)放到可视化的屏幕中,如果当天/当周/当月没有数据,则显示0,形成折线图

背景:
使用Laravel6.0框架开发
单独做出统计表,以天为单位做出点击次数、评论次数、投诉次数进行统计(数据量大的时候,千万不要全表扫描业务表。)

开发:

利用Sql语句比较容易的查出这些数据,但是就难为在了没有的时候数据补0上,当使用foreach挨个比对时,感觉效率太低,于是找到了下面一个办法

代码:
1.显示最近7天的数据展示

 $params = $request->all(); $array = []; $day = 7; for ($i = $day - 1; 0 <= $i; $i--) {     $array[] = date('Y-m-d 00:00:00', strtotime('-' . $i . ' day'));     $nums[] = 0; }  $result =  DB::table('data_insert_days')         ->select([             DB::raw("FROM_UNIXTIME(UNIX_TIMESTAMP(time),'%Y-%m-%d') as date"),             DB::raw('sum(number) AS count'),         ])         ->whereBetween('time', [Carbon::yesterday()->subDays(7), Carbon::now()])         ->groupBy("date")         ->orderBy('date', 'asc')         ->get()         ->toArray();          array_walk($result, function ($value, $key) use ($array, &$nums) {         $index = array_search($value->date,$array);         $nums[$index] = $value->count;     });     $data = [         'date' => $array,         'count' => $nums     ];

那么最终展示数据结构为

{    "data": {        "date": [            "2020-05-19",            "2020-05-20",            "2020-05-21",            "2020-05-22",            "2020-05-23",            "2020-05-24",            "2020-05-25"        ],        "count": [            "36",            "11",            "45",            "49",            "38",            "39",            "1"        ]    },    "Success": true,    "Message": {        "Code": 0,        "Content": "操作成功"    }}

最近6周的数据展示

    $today_week = date('W',time());    $start_week = $today_week-7;    for ($i = $start_week + 1; $i<=$today_week; $i++) {        $array[] = $i;        $nums[] = 0;    }      $result = DB::table('data_insert_days')            ->select(DB::raw('weekofyear(time) as w, SUM(number) as t'))            ->where("site_id",$params['site_id'])            ->whereRaw('time > DATE_SUB(now(), INTERVAL 7 WEEK)')            ->groupBy(DB::raw('weekofyear(time)'))            ->get()            ->toArray();    array_walk($result, function ($value, $key) use ($array, &$nums) {            $index = array_search($value->w,$array);            $nums[$index] = $value->t;        });        $data = [            'w' => $array,            't' => $nums        ];        

以此类推可以算出最近6个月的数据。