即使缺少记录,每天的汇总统计信息

时间:2019-09-26 09:30:19

标签: php mongodb

尝试获取过去x天的统计信息。 除了我没有数据的日子,这行得通。 现在,我可以使用PHP脚本解决此问题,但如果当天没有记录,我宁愿让其计数为“ 0”。

TLDR;我想从今天回到30天之前,即使没有记录(0),也要每天获取记录数量。

    /**
     * Get Multi Count
     */
    public static function getMultiCount() {

        global $mongo;

        $timestamps = [];
        for($i = 30; $i >= 0; $i--) {
            $timestamps[] = date('Y-m-d', strtotime('-'.$i.' days'));
        }

        $result = [];
        foreach(array_keys(self::$config) as $collection) {
            $datecol = self::$config[$collection]['datecol'];
            $ops = [
                [
                    '$group' => [
                        "_id" => [
                            '$dateToString' => [
                                "format" => "%Y-%m-%d",
                                'date' => '$' . $datecol
                            ]
                        ],
                        "count" => [
                            '$sum' => 1
                        ],
                    ]
                ],
                [
                    '$sort' => [
                        '_id' => 1
                    ]
                ],
                [
                    '$match' => [
                        '_id' => [
                            '$in' => $timestamps
                        ]
                    ]
                ]
            ];
            $aggregation = $mongo->aggregate($collection, $ops);
            foreach($aggregation as $k => $values) {
                $result[$collection]['labels'][] = $values['_id'];
                $result[$collection]['counts'][] = $values['count'];
                $result[$collection]['background_colors'][] = "rgba(" . rand(10, 255) . "," . rand(10, 255) . "," . rand(80, 255) . ",0.4)";
            }
        }

        return $result;

    }

我的目标是在30天之内得到类似的东西...

  ["docdata_errors"]=>
  array(3) {
    ["labels"]=>
    array(3) {
      [0]=>
      string(10) "2019-09-10"
      [1]=>
      string(10) "2019-09-17"
      [2]=>
      string(10) "2019-09-19"
    }
    ["counts"]=>
    array(3) {
      [0]=>
      int(2)
      [1]=>
      int(4)
      [2]=>
      int(6)
    }
    ["background_colors"]=>
    array(3) {
      [0]=>
      string(20) "rgba(119,93,143,0.4)"
      [1]=>
      string(20) "rgba(32,150,160,0.4)"
      [2]=>
      string(19) "rgba(92,87,255,0.4)"
    }
  }

尽管由于我整天都没有数据,所以除了未记录的索引外,它将返回30个索引;我没有数据的那些。

1 个答案:

答案 0 :(得分:0)

您可以使用DateTime对象循环而不是使用数据源在数组中创建日期。设置结束日期,并从当前日期开始倒数,直到到达为止。

赞:

$endDate = new DateTime();
$endDate->modify('-29 days');

for($currentDate = new DateTime(); $currentDate > $endDate; $currentDate->modify('-1 day')) {
    // Check if there is data for the current day using $currentDate->format('Y-m-d') to 
    // compare against the date string in your data source.
    // If there is data, use it. Otherwise create an entry from the date in 
    // $currentDate and substitute 0 as the count.
}