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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With