Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate Google chart API dynamically

Tags:

json

php

api

I am trying to create a Google line chart using their API and JSON.

Hard coded, this chart works:

<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Date', 'Sales'],
      ['Jun 25',  12.25],
      ['Jun 26',  8.00],
      ['Jun 27',  20.50]
      ['Jun 28',  12.75]
    ]);

    var options = {

    };

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

</script>

However, trying to populate it using JSON, I can not get this to work:

<?php

$data = array();
$data["Date"] = "Sales";
$data["Jun 25"] = "12.25";
$data["Jun 26"] = "8.00";
$data["Jun 27"] = "20.50";
$data["Jun 28"] = "12.75";
$data = json_encode($data);

?>

<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);

  function drawChart() {

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

    var options = {

    };

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

</script>

I'm obviously not encoding the array correctly. Google has an example page on how to populate their charts with JSON data here: https://developers.google.com/chart/interactive/docs/php_example

However, I could not find any examples for how to setup the JSON data with a simple line chart like this.

like image 601
MultiDev Avatar asked Dec 12 '22 00:12

MultiDev


1 Answers

You're close.

$data = array( 
             array('Date', 'Sales'),  
             array('June 25', 12.25),  
             array('June 26', 8.00) 
);

json_encode($data);

Output

[["Date","Sales"],["June 25",12.25],["June 26",8]]

See it in action.

like image 142
Josh Avatar answered Dec 27 '22 23:12

Josh