简体   繁体   English

排序 arrays 并比较数组值 php

[英]Sorting arrays and comparing array values php

Good day guys, I'm working on plotting data on charts using ChartJs and Laravel, I need to plot data based on months and I want the whole 12 months showing on the chart even without data,大家好,我正在使用 ChartJs 和 Laravel 在图表上绘制数据,我需要基于月份的 plot 数据,我希望即使没有数据也能在图表上显示整个 12 个月,

I have months in an array ['January', 'February'....我有几个月的数组 ['January', 'February'....

Then I have my data here:然后我在这里有我的数据:

     $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);
            }
        }
    }

But the issue is instead of 12 months after the loop I'm getting 24... Duplicates and the data also in 24... I want the months to just match with the data without the duplicates但问题不是循环后的 12 个月,我得到了 24...重复和数据也在 24...我希望月份与没有重复的数据匹配

Try the below code:试试下面的代码:

$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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM