我想使用 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]
我已经编写了生成数组的代码,但错误 undefined offset :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;
}
}
}
最佳答案
你可以尝试这样的事情:
$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
}
关于php - Laravel 每月计数记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47671764/