将Codeigniter PHP数据添加到Chart js

时间:2018-11-12 09:24:39

标签: javascript php codeigniter chart.js

我认为获取数据作为键和值以显示在图表中

<?php foreach ($statistics as $key=>$stat):?>
  <?php echo $key?>
  <?php echo $stat?>
<?php endforeach; ?>

$ statistics 具有如下数据集

  

Array([09-11-2018] => 1 [10-11-2018] => 2 [11-11-2018] => 5)数组   ([09-11-2018] => 1 [10-11-2018] => 2 [11-11-2018] => 5)

图表js脚本如下

<script>
    var ctx = document.getElementById("myChart").getContext("2d");

    var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                  labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
                  datasets: [{
                        label: 'Users',
                        data: [12, 19, 3, 5, 2, 3]
                             }]
                  },
            options: {
            scales: {
                  yAxes: [{
                        ticks: {
                             beginAtZero:true
                               }
                          }]
                    }
           }
       });
  </script>

如何将标签添加为 $ key 数据,如何将数据集数据添加为 $ stat 数据

请帮助我

1 个答案:

答案 0 :(得分:0)

使用以下代码更新您的代码

foreach ($statistics as $key=>$stat){
  $label[]=$key;
  $data[]=$stat;
}

和脚本代码

<script>
  var ctx = document.getElementById("myChart").getContext("2d");
  var labelData='<?php echo json_encode($label); ?>';
  var chartData='<?php echo json_encode($data); ?>'
  var myChart = new Chart(ctx, {
        type: 'line',
        data: {
              labels: labelData,
              datasets: [{
                    label: 'Users',
                    data: chartData
                         }]
              },
        options: {
        scales: {
              yAxes: [{
                    ticks: {
                         beginAtZero:true
                           }
                      }]
                }
       }
   });
</script>