我想使用Chart.js
将JSON数据输出到图表,查询MySQL数据库中的数据。
基本上我要查询的是(data.php):
<?php
header('Content-Type: application/json');
$con = //Database connection
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM condicao order by id desc limit 10");
while($row = mysqli_fetch_array($result))
{
$point = array($row['timestamp'], $row['temperatura']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
这给了我以下数组(timestamp
,temperature
):
[
["2014-08-04 23:06:01",16.9],
["2014-08-04 23:03:02",17.1],
["2014-08-04 23:00:02",17.1],
["2014-08-04 22:57:01",17.1],
["2014-08-04 22:54:01",17.1],
["2014-08-04 22:51:02",17.1],
["2014-08-04 22:48:01",17.2],
["2014-08-04 22:45:02",17.2],
["2014-08-04 22:42:01",17.2],
["2014-08-04 22:39:02",17.2]
]
现在我正在尝试将其输出到图表,但我不知道如何将第一个对象作为标签(时间戳),将第二个对象作为数据点(温度)。
这是我正在尝试输出图表的代码:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("data.php", function (result) {
var tempData = {
labels : result,
datasets : [{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : result
}]
}
var temp = document.getElementById('compradores').getContext('2d');
new Chart(temp).Line(tempData);
});
});
</script>
如何将结果标识为标签的第一个对象(时间戳),将数组中的第二个对象标识为数据点(温度)?
在我上面的方式中,我将时间戳和温度都作为标签。
我已经尝试了result[0]
,尝试为时间戳定义标签并调用result['timestamp']
等等,但没有运气。
谢谢!
答案 0 :(得分:9)
问题是你必须在单独的集合中提供timeStamp / temperature,就像在与之关联的标签和数据集中一样。
你可以回复&#34;结果&#34;分别分为两个两个数组:
[["16.9", "17.1", "17.1", "17.1", "17.1", "17.1", "17.2", "17.2", "17.2", "17.2"],
["2014-08-04 23:06:01", "2014-08-04 23:03:02", "2014-08-04 23:00:02", "2014-08-04 22:57:01", "2014-08-04 22:54:01", "2014-08-04 22:51:02", "2014-08-04 22:48:01", "2014-08-04 22:45:02", "2014-08-04 22:42:01", "2014-08-04 22:39:02"]];
然后你就可以了,
var tempData = {
labels : result[0],
datasets : [{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : result[1]
}]
};
或者你可以将它转换成前端的两个数组。
例如:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("data.php", function (result) {
var labels = [],data=[];
for(var item in result){
labels.push(result[item].slice(0,1).toString());
data.push(result[item].slice(1,2).toString());
}
var tempData = {
labels : labels,
datasets : [{
fillColor : "rgba(172,194,132,0.4)",
strokeColor : "#ACC26D",
pointColor : "#fff",
pointStrokeColor : "#9DB86D",
data : data
}]
};
var temp = document.getElementById('compradores').getContext('2d');
var lineChart = new Chart(temp).Line(tempData);
});
});
</script>