gpt4 book ai didi

javascript - 谷歌图表和 JSON 数据

转载 作者:行者123 更新时间:2023-11-30 06:52:16 25 4
gpt4 key购买 nike

我不是 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 的图表 API 将这些数据输入折线图中?我试过使用这个例子,但它不起作用。 ( https://developers.google.com/chart/interactive/docs/gallery/linechart )

最佳答案

首先按照 google charts 要求的格式定义数组:

$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 Example )

    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

?>

关于javascript - 谷歌图表和 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35537550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com