I’ve a function which feeds a chart with fixed data:
function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'CPU Temp'], ['2004', 340], ['2005', 460], ['2006', 1120], ['2007', 540] ]); }
I’d like to replace the fixed data with the one read from a DB table containing two columns: date
and temperature
. The read data is stored in the $json
variable:
[ {"datain":"2021-04-20 12:00:03","temp":"39.2"}, {"datain":"2021-04-21 00:00:05","temp":"40.2"}, {"datain":"2021-04-21 12:00:03","temp":"40.8"}, {"datain":"2021-08-01 12:00:12","temp":"47.2"} ]
Here’s my bad code:
let date= ""; let temp = ""; for (let i = 0; i < <?php echo count($json)?>; i++){ date = <?php echo $json[0] ?>; temp = <?php echo $json[1] ?>; } function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'CPU Temp'], [date, temp] ]); }
How can I make this work?
EDIT: Code after being edited with @trincot’s suggestions:
< script type = "text/javascript" > google.charts.load('current', { 'packages': ['corechart'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Temp'], ...<?php echo $json; ?>.map(({ datain, temp }) => [new Date(datain), parseFloat(temp)]) ]); var options = { title: 'CPU Temp History', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } < /script>
Original code is here:chart code
Advertisement
Answer
Given that your $json
is an array of objects with two properties, you’ll need to convert that to an array of arrays (pairs):
function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'CPU Temp'], ...<?php echo $json; ?>.map(({datain, temp}) => [new Date(datain), +temp]) ]); }
So this just injects the whole JSON inside the array literal that is given as argument to arrayToDataTable
. The .map
call converts the plain objects to pairs and:
- the date strings are converted to
Date
objects - the temperature strings are converted to numbers. It is a pity that your PHP code has somehow stored the temperatures as strings. That is odd. It would be better practice to have them there with a number data type, not a string data type.
When you look at the source via your browser, you should see something like this:
function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'CPU Temp'], ...[{"datain":"2021-04-20 12:00:03","temp":"39.2"},{"datain":"2021-04-21 00:00:05","temp":"40.2"},{"datain":"2021-04-21 12:00:03","temp":"40.8"},{"datain":"2021-08-01 12:00:12","temp":"47.2"}].map(({datain, temp}) => [new Date(datain), +temp]) ]); }