大家好,我正在使用ChartJs和Laravel在图表上绘制数据,我需要基于月份来绘制数据,我希望整个12个月即使没有数据也可以在图表上显示,
我在数组中有几个月['January','February'....
然后我的数据在这里:
$stats = DB::table('wallet_payouts')
->groupBy('date')
->orderBy('date', 'ASC')
->get([
DB::raw('DATE_FORMAT(created_at, "%M") as date'),
DB::raw('COUNT(*) as value')
]);
$labels = [];
$data = [];
foreach ($months as $month){
foreach ($stats as $stat){
if ($month == $stat->date){
array_push($labels, $stat->date);
array_push($data, $stat->value);
}else{
array_push($labels, $month);
array_push($data, 0);
}
}
}
但是问题不是循环后的12个月,而是24个……重复项,数据也有24个...我希望这些月仅与没有重复项的数据相匹配
尝试以下代码:
$stats = DB::table('wallet_payouts')
->groupBy('date')
->orderBy('date', 'ASC')
->get([
DB::raw('DATE_FORMAT(created_at, "%M") as date'),
DB::raw('COUNT(*) as value')
]);
$labels = $months;
$data = [];
$temp = [];
foreach ($stats as $stat){
$temp[$stat->date] = $stat->value;
}
foreach($months as $month){
if(array_key_exists($month,$temp)){
array_push($data, $temp[$month]);
} else {
array_push($data, 0);
}
}