• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

最近6天6周6月的数据统计没有补0的需求

php 搞代码 4年前 (2022-03-01) 24次浏览 已收录 0个评论

最近接到一个需求:
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个月的数据。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:最近6天6周6月的数据统计没有补0的需求

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址