我有来自我的树莓派气象站的数据,这些数据被推送到我自己的mysql服务器上。 数据如下所示:
有了这些数据,我想创建一个谷歌图表来可视化。 我的问题是我无法使用日期时间,因为谷歌期望某种特殊格式。自从这些天以来,我在 stackoverflow 上阅读了大量文章,但互联网上没有一个真正有效的例子。
到目前为止我所做的是:
1)从SQL读取数据并格式化为JSON
$conn = mysqli_conn--ect('192.168.178.39', '-', '---!', 'wetterstation');
$sql = 'SELECT cur_datum, Temperatur_DPS310 FROM Outdoor';
$result = mysqli_query($conn, $sql);
foreach($result as $r) {
$temp = array();
// The following line will be used to slice the chart
$temp[] = array('cur_datum' => 'Date('.date('Y',strtotime($r['cur_datum'])).',' .
(date('n',strtotime($r['cur_datum'])) - 1).','.
date('d',strtotime($r['cur_datum'])).','.
date('H',strtotime($r['cur_datum'])).','.
date('i',strtotime($r['cur_datum'])).','.
date('s',strtotime($r['cur_datum'])).')');
// Values of the each slice
$temp[] = array('Temperatur_DPS310' => (double) $r['Temperatur_DPS310']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
$jsonTable = json_encode($table);
--> JSON 格式似乎没问题
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
title: 'Testest',
curveType: 'function',
legend: { position: 'bottom' },
tooltip: {isHtml: true}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
} // drawChart
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:400; height:300"></div>
</body>
</html>
--> 没有可见的谷歌图表,通常这意味着存在错误......不幸的是谷歌不让我看到错误消息,也许我太愚蠢而无法显示错误消息......:)
通过以下示例,我能够创建谷歌图表:
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('datetime', 'Time');
dataTable.addColumn('number', 'Price (Euro)');
dataTable.addRows([
[new Date(2014, 6, 2, 9, 0, 0, 0), 21.40],
[new Date(2014, 6, 2, 11, 0, 0, 0), 21.39],
[new Date(2014, 6, 2, 13, 0, 0, 0), 21.20],
[new Date(2014, 6, 2, 15, 0, 0, 0), 21.22],
[new Date(2014, 6, 2, 17, 0, 0, 0), 20.99],
[new Date(2014, 6, 2, 17, 30, 0, 0), 21.03],
[new Date(2014, 6, 3, 9, 0, 0, 0), 21.05],
[new Date(2014, 6, 3, 11, 0, 0, 0), 21.07],
[new Date(2014, 6, 3, 13, 0, 0, 0), 21.10],
[new Date(2014, 6, 3, 15, 0, 0, 0), 21.08],
[new Date(2014, 6, 3, 17, 0, 0, 0), 21.05],
[new Date(2014, 6, 3, 17, 30, 0, 0), 21.00],
[new Date(2014, 6, 4, 9, 0, 0, 0), 21.15],
[new Date(2014, 6, 4, 11, 0, 0, 0), 21.17],
[new Date(2014, 6, 4, 13, 0, 0, 0), 21.25],
[new Date(2014, 6, 4, 15, 0, 0, 0), 21.32],
[new Date(2014, 6, 4, 17, 0, 0, 0), 21.35],
[new Date(2014, 6, 4, 17, 30, 0, 0), 21.37],
]);
// Instantiate and draw our chart, passing in some options.
// var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {
title : 'AEX Stock: Nationale Nederlanden (NN)',
width : 1400,
height : 540,
legend : 'true',
pointSize: 5,
vAxis: { title: 'Price (Euro)', maxValue: 21.50, minValue: 20.50 },
hAxis: { title: 'Time of day (Hours:Minutes)', format: 'HH:mm', gridlines: {count:9} }
};
var formatNumber = new google.visualization.NumberFormat(
{prefix: '', negativeColor: 'red', negativeParens: true});
var formatDate = new google.visualization.DateFormat(
{ prefix: 'Time: ', pattern: "dd MMM HH:mm", });
formatDate.format(dataTable, 0);
formatNumber.format(dataTable, 1);
chart.draw(dataTable, options);
--> 手动数据适用于这种格式。现在我想用 SQL 数据创建该格式 手动数据示例
第二次尝试模仿手动数据:
if ($result !== false) {
$output = Array();
while ($row = mysqli_fetch_assoc($result)) {
$DateTimeArray = $row["cur_datum"];
$MYvalue1 = $row["Temperatur_DPS310"];
$date = date('Y-m-d', strtotime($DateTimeArray));
$time = date('H:i:s', strtotime($DateTimeArray));
$dateArray = explode('-', $date);
$year = $dateArray[0];
$month = $dateArray[1] - 1; // adjust for javascript's 0-indexed months
$day = $dateArray[2];
$timeArray = explode(':', $time);
$hours = $timeArray[0];
$minutes = $timeArray[1];
$seconds = $timeArray[2];
$output[] = "[new Date($year,$month,$day,$hours,$minutes,$seconds), $MYvalue1]";
}
}
输出看起来与手动数据完全一样:
控制台错误:
请帮忙!
我建议您
json_encode
原始数据库查询结果,而不是在 PHP 中执行特殊的日期时间操作 - The following line will be used to slice the chart
是什么意思?数据库中保存的格式看起来非常适合与 Google Charts / DataTable 一起使用 - javascript 将能够将返回的字符串值转换为可用的 date
对象,并将温度值转换为浮点数。
在测试中(使用自己的数据来模拟)打印到页面的 JSON 如下所示:
const json=[
{
"Temperatur_DPS310": "194",
"cur_datum": "2022-10-31 15:54:00"
},
{
"Temperatur_DPS310": "150",
"cur_datum": "2022-11-02 16:08:00"
},
{
"Temperatur_DPS310": "143",
"cur_datum": "2022-11-02 16:09:21"
},
{
"Temperatur_DPS310": "153",
"cur_datum": "2022-11-02 16:21:14"
} //.........etc ( temperatures as fictitious )
以及查询数据库并渲染图表的页面
<?php
#dbconn required
$sql='SELECT `cur_datum`, `Temperatur_DPS310` FROM `Outdoor`';
$res=$db->query( $sql );
$data=array();
while( $rs=$res->fetch_assoc() )$data[]=$rs;
$json=json_encode( $data, JSON_PRETTY_PRINT );
?>
<html>
<head>
<script src='https://www.gstatic.com/charts/loader.js'></script>
<script>
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback( drawChart );
<?php
printf('
const json=%s;
',$json
);
?>
function drawChart() {
// create the empty datatable and add two columns
let dataTbl = new google.visualization.DataTable();
dataTbl.addColumn('datetime', 'Time');
dataTbl.addColumn('number', 'Price (Euro)');
// recordset has two columns per record
// create each record as an array and let the dataTbl add them
Object.keys( json ).forEach(key=>{
let row=json[ key ];
let rs=[
new Date( row.cur_datum ),
parseFloat( row.Temperatur_DPS310 )
];
dataTbl.addRow( rs )
})
let options = {/* a mix of optios from the question */
title : 'AEX Stock: Nationale Nederlanden (NN)',
width : 1400,
height : 540,
legend : 'true',
curveType: 'function',
pointSize: 5,
vAxis: { title: 'Price (Euro)', maxValue: 21.50, minValue: 20.50 },
hAxis: { title: 'Time of day (Hours:Minutes)', format: 'HH:mm', gridlines: {count:9} },
tooltip: {isHtml: true}
};
var chart = new google.visualization.LineChart( document.getElementById('chart_div') );
chart.draw( dataTbl, options );
}
</script>
</head>
<body>
<div id='chart_div' style='width:1500; height:600'></div>
</body>
</html>
上面的代码,使用自己的数据,渲染出如下图表:
看起来我已经太晚了,但就其价值而言,我认为你的drawChart()函数中的这一行
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
应该是
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));