如何在Laravel中动态解决Chart js不匹配的x轴标签和值? [英] How to solve Chart js mismatched x-axes label and value dynamically in Laravel?

查看:134
本文介绍了如何在Laravel中动态解决Chart js不匹配的x轴标签和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在动态应用图js时遇到问题,这意味着我从数据库中获取数据并使用图JS输出条形图。我发现该示例在值为0时有效,但根据我的情况,我的数据库中仍找不到特定年份的某些数据,这导致值为空。如何将此空值或null值设置为零,以便可以实现此示例



条形图所基于的数据库表



解决方案

我认为 $ female数据不匹配的问题 $ male 具有JS年变量。

  var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010', '2011','2012','2013','2014','2015','2016','2017','2018','2019','2020']]; 
var female =<?php echo $ female; ?> ;;
var male =<?php echo $ male; ?> ;;

如果 $ female ,则传递 0或 $ male 没有每年的价值(假设2000年)。因此,您的 $ female $ male 应该像:

  var year = ['2000','2001','2002','2003','2004'...]; 
var female = ['0','34','0','65','54',...];
var male = ['0','75','0','34','0',...];



更新



在下面的代码中尝试使用控制器端的完整代码段。将 enroll 替换为数据库表名称到该查询中。

  $ rsltEnrollData = DB :: table('enroll')-> selectRaw('sy as sy,sex,SUM(tot_enroll)as count')
-> groupBy('sy')
-> orderBy('sy')
-> get();

$ arrFemale = array();
$ arrMale = array();
$ arrYearData = array();
foreach($ rsltEnrollData as $ key => $ objEnrollData){

if(!isset($ arrYearData [$ objEnrollData-> sy])){
$ arrYearData [$ objEnrollData-> sy] ['Male'] = 0;
$ arrYearData [$ objEnrollData-> sy] [’Female’] = 0;
}
$ arrYearData [$ objEnrollData-> sy] [$ objEnrollData-> gender] = $ objEnrollData-> count;
$ arrFemale = $ arrYearData [$ objEnrollData-> sy] [’Female’];
$ arrMale = $ arrYearData [$ objEnrollData-> sy] [’Male’];
}



调试



  foreach($ rsltEnrollData as $ key => $ objEnrollData){
print('< pre style = color:red;>');
print_r($ objEnrollData);
print(’< / pre>’);
}
出口;


I have encountered a problem using chart js when applying it dynamiccally, which means I get a data from my database and output a bar graph using Chart JS. I found this example which works when a value is 0, but on my situation some data on a specific year cannot be found yet on my database, which leads to a null value. How can I set this empty or null value to zero so that I can achieve this example https://jsfiddle.net/17mw40rx/1/. I want also to show my JS code which I copied from the same sample and applied it to my project. The script works fine but when a year data is missing let say no record found in 2002 and 2005, the data are filled automatically by a wrong year data. I hope you understand my problem. Please I need help from someone about this.

JS Script

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<script>

var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'];
var female = <?php echo $female; ?>;
var male = <?php echo $male; ?>;

var entranceDataset = {
              label: 'Female',
              type: 'bar',
              yAxesID : "y-axis-1",
              data: female,
              backgroundColor: 'rgba(0, 204, 0, 0.2)',
              borderColor: 'rgba(0, 204, 0,1)',
              borderWidth: 1
          };

    var dataset = [];
    dataset.push(entranceDataset);

      var exitDataset = {
                label: 'Male',
                type: 'bar',
                yAxesID : "y-axis-1",
                data: male,
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 1
            };

      dataset.push(exitDataset);

    var ctx = $('#enrollcanvas');

    mainThroughputChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: year,
            datasets: dataset
        },
        options: {
            scales: {
                xAxes : [{
                  gridLines : {
                        display : false
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Year'
                      }
                }]
            },

        }
    });
</script>

Laravel Controller and query

$female = Enroll::select(DB::raw("SUM(tot_enroll) as count"))
            ->orderBy(DB::raw('sy'))
            ->groupBy(DB::raw("(sy)"))
            ->where('gender','=', 'Female')
            ->get()->toArray();
            $female = array_column($female, 'count');

  $male = Enroll::select(DB::raw("SUM(tot_enroll) as count"))
            ->orderBy(DB::raw('sy'))
            ->groupBy(DB::raw("(sy)"))
            ->where('gender','=', 'Male')
            ->get()->toArray();
             $male = array_column($male, 'count');

return view('home')
        ->with('female',json_encode($female,JSON_NUMERIC_CHECK))
        ->with('male',json_encode($male,JSON_NUMERIC_CHECK));

Blade Page

<canvas id="enrollcanvas" name="enrollcanvas" height="280" width="600"></canvas>

Actual Bar Chart Result

Database Table where the bar chart is based from

解决方案

I think the problem with mismatched data of $female and $male with JS year variable.

var year = ['2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020'];
var female = <?php echo $female; ?>;
var male = <?php echo $male; ?>;

Pass the '0' if $female OR $male doesn't have value for each year(Let's say 2000). So your $female and $male should be like:

var year = ['2000','2001','2002','2003', '2004'...];
var female = ['0','34', '0','65', '54',...];
var male = ['0','75', '0','34', '0',...];

Update

Try this below code with full snippet of controller side. Replace enroll with your database table name into this query.

$rsltEnrollData = DB::table('enroll')->selectRaw('sy as sy, gender, SUM(tot_enroll) as count')
->groupBy('sy')
->orderBy('sy')
->get();

$arrFemale = array();
$arrMale = array();
$arrYearData = array();
foreach($rsltEnrollData as $key => $objEnrollData){

    if(!isset($arrYearData[$objEnrollData->sy])){
        $arrYearData[$objEnrollData->sy]['Male'] = 0;
        $arrYearData[$objEnrollData->sy]['Female'] = 0;
    }
    $arrYearData[$objEnrollData->sy][$objEnrollData->gender] = $objEnrollData->count;
    $arrFemale = $arrYearData[$objEnrollData->sy]['Female'];
    $arrMale = $arrYearData[$objEnrollData->sy]['Male'];
}

Debug

foreach($rsltEnrollData as $key => $objEnrollData){
 print('<pre style="color:red;">');
 print_r($objEnrollData);
 print('</pre>');
}
exit;

这篇关于如何在Laravel中动态解决Chart js不匹配的x轴标签和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆