最近接到一個需求:
1.要求作一些大屏數據展現,數據可視化,將用戶的一些數據(例如評論次數、投訴次數)放到可視化的屏幕中,若是當天/當週/當月沒有數據,則顯示0,造成折線圖數據結構
背景:
使用Laravel6.0框架開發
單獨作出統計表,以天爲單位作出點擊次數、評論次數、投訴次數進行統計(數據量大的時候,千萬不要全表掃描業務表。)框架
開發:code
利用Sql語句比較容易的查出這些數據,可是就難爲在了沒有的時候數據補0上,當使用foreach挨個比對時,感受效率過低,因而找到了下面一個辦法開發
代碼:
1.顯示最近7天的數據展現get
$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 ];
那麼最終展現數據結構爲it
{ "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周的數據展現io
$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個月的數據。table