Laravel每月统计记录

时间:2017-12-06 10:14:13

标签: php algorithm laravel

我想使用Laravel的Chartjs创建月度统计数据。

$monthly_uploaded_product = DB::table('author_product')
         ->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
         ->groupBy('month')
         ->get();

查询的结果是:

[{"total":1,"month":10},{"total":17,"month":11}]

代码的输出应该像这样用Javascript(Chartjs)表示:

[0,0,0,0,0,0,0,0,0,1,17,0]

我已编写代码来生成数组,但错误未定义的偏移:1

$statistics_monthly_product = array();   
foreach (range(1, 12) as $month) {
    foreach ($monthly_uploaded_product as $key) {
        if ($statistics_monthly_product[$month] == $key->month){
            $statistics_monthly_product[$month] = $key->total;
        }else{
            $statistics_monthly_product[$month] = 0;
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

$year = [0,0,0,0,0,0,0,0,0,0,0,0];//initialize all months to 0

foreach($monthly_uploaded_product as $key)
   $year[$key->month-1] = $key->total;//update each month with the total value
}

答案 1 :(得分:0)

$statistics_monthly_product = array();行创建一个新数组。这意味着当您稍后循环并尝试执行$statistics_monthly_product[$month]时,您将尝试访问空数组的索引$month。这将始终为您提供未定义索引的错误,因为数组中根本没有任何内容。

也许您可以先使用一些默认值初始化数组:

$statistics_monthly_product = [0,0,0,0,0,0,0,0,0,0,0,0];

答案 2 :(得分:0)

此代码返回您期望的数组     

$data = [["total" => 1,"month" => 10],["total" => 17,"month" => 11]]; 
$monthTotals = [];

foreach($data as $item){
    $monthTotals[$item["month"]] = $item["total"];
}

$chartJSCompat = [];
for($i = 0;$i < 12;$i++){
    if(isset($monthTotals[$i+1]))
        $chartJSCompat[$i] = $monthTotals[$i+1];
    else
        $chartJSCompat[$i] = 0;
}

var_dump($chartJSCompat);