How to dynamically populate the Google chart API

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

Hard code, this graph 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 with JSON, I cannot 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 am obviously not correctly coding the array. Google provides an example page on how to populate your charts with JSON data here: https://developers.google.com/chart/interactive/docs/php_example

However, I could not find examples of how to set up JSON data with a simple line chart.

+4
source share
3 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]] 

Look in action.

+13
source

Josh has already given the correct answer. But if you want to use google.visualization.DataTable instead of google.visualization.arrayToDataTable , you can add the columns separately first and then add the json encoded php array:

 var data = new google.visualization.DataTable(); data.addColumn('string', 'Date'); data.addColumn('string', 'Sales'); data.addRows(<?php echo $data; ?>); 
0
source
 while($fetch = sqlsrv_fetch_array( $result, SQLSRV_FETCH_BOTH)) { $grid[$count]= $fetch['Hour']; $grid1[$count]=$fetch['Revenue']; $data[$count]=array($fetch['Hour'],$fetch['Revenue']); $count++; } $num=$count; $data[0] = array('Hours','Revenue'); for ($i=0; $i<($num+1); $i++) { $data[$i]=(array('c' => array(array('v' => (string)$grid[$i]), array('v' =>(int)($grid1[$i]) ), ) )); } $sample=array(array('type' => 'string', 'label' => 'date'),array('type' => 'number', 'label' => 'Amount')); $table['cols'] = $sample; $table['rows'] = $data; echo (json_encode($table )); 

This worked for me if you format your json so that it will definitely work

0
source

All Articles