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
$json
? Can you give explicit sample data in PHP or JSON format?