TrackmeifYouCan
TrackmeifYouCan

Reputation: 108

charts labels and data with php arrays

When I pass the array as an argument to the chart it stops showing on the web page.

<?php
$f = fopen("C:\wamp64\www\dashb\CSV\salespermonthdollars.csv", "r");
$labels = array();
$data = array();
$loopCounter = 0;
while (($line = fgetcsv($f)) !== false) {
  if($loopCounter == 0){
    // this if is to skip the first row or the columns
  } else {
    array_push($labels,$line[0]);
    array_push($data,$line[1]);
  }
  $loopCounter = $loopCounter + 1; 
}
fclose($f); 
?>

So above I read the csv file that I save from my query result and try to plot it on a chart:

<canvas id="myChart2">
<script>
$array3 = [1,2,3,4,5,5,41]; 
$array4 = [1,2,3,4,5,5,41];
var ctx = document.getElementById('myChart2').getContext('2d');
var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: $array3, //when i change this to $labels doesn't work same for4
    datasets: [{
      label: 'label',
      data: $array4,
      backgroundColor: "rgba(100,255,51,0.4)"
     }]
  }
    });
</script>
</canvas>

Mainly I am displaying query result on a chart. I execute, save to csv and read
from there.

Any suggestions for improvement in the approach are welcome, somehow I feel it could be done easier than this.

Upvotes: 0

Views: 1310

Answers (1)

wscourge
wscourge

Reputation: 11281

It is because $labels is not Javascript, but PHP variable. So what you need to do is to decode it in php part of your code:

...
fclose($f); 
$labels = json_decode($label);

And in Javascript part:

var labels = JSON.parse("<?php echo $labels; ?>");

As part of suggestions of improvement goes, you should not declare global variables. So what you are doing here:

$array3 = [1,2,3,4,5,5,41]; 
$array4 = [1,2,3,4,5,5,41];

Should be:

var array3 = [1,2,3,4,5,5,41]; 
var array4 = [1,2,3,4,5,5,41];

I removed $ - dollars from their names, because it's common practice to declare jQuery wrapper variables and those are obviously not. Also, by $ prefix to their names, I can only guess that what you wanted to do was to declare php variables inside your <script> and then use them directly, but it is not possible, because first of all, you are missing <?php part, and second - they would be only saved in the memory by just declaring them.

Upvotes: 1

Related Questions