Google chart SQL and Json

2019-09-05 05:19发布

问题:

Looking to add SQL insert into my google charts. I looked at the google example in the API, however that uses a set file containing the values. I have seen a few examples on here but they seem rather complicated.

I want to populate the chart with data from my DB, im using depreciated code, its just an example. I have read about using json_encode. However when I apply it to my output I get quotations which according to the google example below are not needed.

In short how would I go about getting this simple query displaying in the chart below?

Query example

while($row = mysqli_fetch_array($result))
 {
   $data1[]=    "['" . $row1['Date'] . "','" . $row1['SpeciesB'] . "']";
   echo   "['" . $row['Date'] . "','" . $row['SpeciesA'] . "','" . $row['SpeciesB'] . "'],";
 echo "<br>";
 }

Outputs

 ['2013-08-06','1','1'],
 ['2013-08-13','1','2'],
 ['2013-08-20','2','2'],
 ['2013-08-27','3','1'],
 ['2013-09-17','4','1'],

or

print_r($data1);

  Array ( [0] => ['2013-08-06','1'] [1] => ['2013-08-13','2'] [2] => ['2013-08-20','2'] [3] => ['2013-08-27','1'] [4] => ['2013-09-17','1'] ) 

Example of what google expects

<script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Species A', 'Species B'],
      ['20/05/2006',  1,      1],
      ['20/06/2006',  3,      2],
      ['20/07/2006',  2,      2],
      ['20/08/2006',  3,      1]
    ]);

    var options = {
      title: 'Site Dynamics'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
</script>      

回答1:

You want to use json_encode to take care of the details of building your output for you, as your current method will run into problems in Internet Explorer (you will always have a training comma after your last row of data, which will cause IE to bomb). Try this instead:

$dataArray = array(array('Date', 'Species A', 'Species B'));
while($row = mysqli_fetch_array($result)) {
    // parse the "SpeciesA" and "SpeciesB" values as integer (int) or floating point (float), as appropriate
    $dataArray[] = array($row['Date'], (int) $row['SpeciesA'], (int) $row['Speciesb']);
}

and in the javascript:

var data = google.visualization.arrayToDataTable(<?php echo json_encode($dataArray); ?>);