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.
source share