[英]Google Charts and JSON data
我不是JS专家,我为气象站开发了一个小型界面。 我有一个服务器端代码,可为图形生成JSON数据。 看起来像这样:
[
{
"temperature": "32.1",
"humidity": "91",
"battery": "100",
"time": "2016-02-21 15:28:56"
},
{
"temperature": "32.1",
"humidity": "99.3",
"battery": "100",
"time": "2016-02-21 15:28:47"
},
{
"temperature": "22.2",
"humidity": "70.2",
"battery": "88.2",
"time": "2016-02-21 15:28:19"
},
{
"temperature": "21.2",
"humidity": "88.1",
"battery": "90.4",
"time": "2016-02-21 15:28:22"
}
]
如何使用Google的Chart API将这些数据输入折线图中? 我尝试使用该示例,但它不起作用。 ( https://developers.google.com/chart/interactive/docs/gallery/linechart )
Google图表期望使用以下格式的JSON:
{
"cols": [
{"id":"","label":"temperature","pattern":"","type":"number"},
{"id":"","label":"humidity","pattern":"","type":"number"},
{"id":"","label":"battery","pattern":"","type":"number"},
{"id":"","label":"time","pattern":"","type":"date"}
],
"rows": [
{"c":[{"v":"32.1","f":null},{"v":99.3,"f":null},{"v":100,"f":null},{"v":2016-02-21 15:28:47,"f":null}]}
]
}
json格式不正确。 Google图表期望其图表使用特定的json类型。 我假设您的数据库是mysql。 如果没有,我可以随时修改以下代码。 我创建了一个小型库来执行这些烦人的任务。 所以这里是:
<?php
function generate_GChart_cols($result) {
$fieldcount = mysqli_num_fields($result);
$stringVal = [253]; // MySQL field type codes -See http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$numericVal = [246, 8]; // MySQL field type codes -See http://php.net/manual/en/mysqli-result.fetch-field-direct.php
$colsarray = array();
for ($i = 0; $i < $fieldcount; $i++) {
$finfo = mysqli_fetch_field_direct($result, $i);
switch ($finfo->type) {
case in_array($finfo->type, $stringVal):
$type = 'string';
break;
case in_array($finfo->type, $numericVal):
$type = 'number';
break;
default:
$type = 'string';
}
// Constructs the column array
$colsarray[] = array(
'label' => $finfo->name,
'type' => $type
);
}
return $colsarray;
}
function generate_GChart_rows($result) {
$fieldcount = mysqli_num_fields($result);
$rows = array();
while ($r = $result->fetch_row()) {
$temp = array();
for ($j = 0; $j < $fieldcount; $j++) {
$temp[] = array(
'v' => $r[$j]
);
}
$rows[] = array(
'c' => $temp
);
};
return $rows;
}
?>
一个使用示例为:
<?php
header('content-type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin:*'); //Include this header to make the requests cross-origin
include 'dbconnect.php';
include 'generate_google_json.php';
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = // Your query here - e.g SELECT * FROM TABLE // ;
$result = $conn->query($sql);
$table['data']['rows'] = generate_GChart_rows($result); // Call to function to generate rows
$table['data']['cols'] = generate_GChart_cols($result); // Call to function to generate columns
$conn->close(); // Close db connection
// We echo the json and enforce a numeric check on the values
echo $_GET['callback'] . '(' . json_encode($table, JSON_NUMERIC_CHECK) . ')';
?>
示例输出为:
?(
{
data:{
rows:[
{
c:[
{
v:3123600
},
{
v:3116452
}
]
}
],
cols:[
{
label:2013,
type:"number"
},
{
label:2014,
type:"number"
}
]
}
}
)
如果您使用bigint,varchart和decimal以外的其他类型,则可能要向$ stringVal和$ numericVal数组添加更多值:)
干杯
首先,以Google图表所需的格式定义数组:
$resultsarray = array(
'cols' => array(
array('label' => 'temperature', 'type' => 'number'),
array('label' => 'humidity', 'type' => 'number'),
array('label' => 'battery', 'type' => 'number'),
array('label' => 'time', 'type' => 'date'),
),
'rows' => array()
);
然后将数据添加到您的数组中:
$resultsarray['rows'][] = array('c' => array( array('v'=> 'tempvalue'), array('v'=>'humidityval'), array('v'=>'batteryval'),array('v'=>'timeval')));
编码为JSON并写入文件:
$fp = fopen('data.json', 'w');
//JSON encode and write array to file
fwrite($fp, json_encode($resultsarray, JSON_NUMERIC_CHECK));
fclose($fp);
然后,在您的JavaScript中,您需要:(按照Google的示例 )
function drawChart() {
var jsonData = $.ajax({
url: "getData.php",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
然后是getdata.php的内容(按照Google示例)
<?php
// This is just an example of reading server side data and sending it to the client.
// It reads a json formatted text file and outputs it.
$string = file_get_contents("data.json");
echo $string;
// Instead you can query your database and parse into JSON etc etc
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.