ajax/json 和 PHP 的 Highcharts 数据系列问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8058136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Highcharts data series issue with ajax/json and PHP
提问by gtr1971
This is my first request here, and I've read many of the other related posts on this same issue, but I'm STILL getting stuck and pretty much at my wits end on this... So any help is much appreciated!
这是我在这里的第一个请求,我已经阅读了许多关于同一问题的其他相关帖子,但我仍然陷入困境,并且在这方面几乎无所适从......所以非常感谢任何帮助!
I've got the following Highcharts object on Page1.php, and I'm using AJAX to get data from Page2.php on page load as well as when a dropdown option is changed.
我在 Page1.php 上有以下 Highcharts 对象,我使用 AJAX 从 Page2.php 获取页面加载时以及下拉选项更改时的数据。
(truncated for ease of reading):
(为便于阅读而截断):
$(document).ready(function() {
var e = document.getElementById("selOption"); //<--- This is the dropdown
var domText = e.options[0].text;
var domID = e.options[e.selectedIndex].value;
var options = {
chart: {
renderTo: 'linechart',
type: 'line'
},
title: {
text: 'Title for ' + domText
},
subtitle: {
text: ''
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b %e, %Y',
year: '%Y'
}
},
yAxis: {
title: {
text: 'Important Values'
},
reversed: true,
min: 0,
max: 100
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%b %e', this.x) +': '+ this.y;
}
},
series: []
};
$.get('Page2.php?domID=' + domID,function(data) {
$.each(data, function(key,value) {
//var series = {};
//series.name.push(value);
//series.data.push([value]);
options.series.push(data);
//alert(data);
});
var linechart = new Highcharts.Chart(options);
});
});
Page2.php has the following sending back the json:
Page2.php 具有以下发送回 json 的内容:
$sqlSelect = "SELECT Item1,Item2,Item3 FROM... ";
$result = mysql_query($sqlSelect);
while ($item = mysql_fetch_assoc($result)) {
$name = $item['Item1'];
$date = str_replace("-",",",$item['Item2']);
$pos = $item['Item3'];
$arr = array("name"=>$name,"data"=>"[Date.UTC(".$date."), ".$pos." ],");
echo json_encode($arr);
}
My json return looks like this:
我的 json 返回如下所示:
{"name":"Item1","data":"[Date.UTC(2011,11,08), 4 ],"}
{"name":"Item1","data":"[Date.UTC(2011,11,08), 2 ],"}
When my chart loads, it fills in 135 Series names (?!?!?!) at the bottom and doesn't appear to show the points on the line graph.
当我的图表加载时,它会在底部填充 135 个系列名称 (?!?!?!),并且似乎没有显示折线图上的点。
If I remove the double quotes and hard code the result into the series array, it works great (though I noticed the example doesn't appear to have a comma between the objects.
如果我删除双引号并将结果硬编码到系列数组中,则效果很好(尽管我注意到该示例在对象之间似乎没有逗号。
THANK YOU for all help ...especially quick replies! ;-)
感谢您的所有帮助...尤其是快速回复!;-)
回答by gtr1971
SOLVED:
解决了:
I found an answer that finally worked! Frustrating that it took me several days because it wasn't well documented by Highcharts (and/or maybe my understanding of jQuert and JavaScript is still at a novice level).
我找到了一个最终有效的答案!令人沮丧的是,我花了几天时间,因为 Highcharts 没有很好地记录它(和/或我对 jQuert 和 JavaScript 的理解仍处于新手级别)。
The answer is do notsend the X/Y data as a preformed array in your json object, but instead simply send the numbers that make up the Date (x value) and the Value (y value) as a list of comma separated values in a json object, and then do the parsing and pushing on the client end.
答案是不要将 X/Y 数据作为 json 对象中的预制数组发送,而只是将构成日期(x 值)和值(y 值)的数字作为逗号分隔值的列表发送一个json对象,然后在客户端做解析和推送。
For example:I originally was trying to get my PHP to send something like
例如:我最初试图让我的 PHP 发送类似
[{"name":"Name 1","data":["[Date.UTC(2011,11,08), 4 ]","[Date.UTC(2011,11,09), 4 ]","[Date.UTC(2011,11,10), 4 ]","[Date.UTC(2011,11,11), 4 ]","[Date.UTC(2011,11,14), 3 ]"]}
but what I really needed to do was send something like
但我真正需要做的是发送类似
[{"name":"Name 1","data":["2011,11,08, 4","2011,11,09,4"....`
The first step is to make sure you have the "series" option set to an empty array series: []
第一步是确保将“系列”选项设置为空数组 series: []
(I mention this because I've seen other answers where this was done differently).
(我提到这一点是因为我已经看到其他答案的不同之处)。
Then in your getJSON function, you need to create a new object for each object you're pulling in, which also includes an empty "data" array (see "var series" below).
然后在您的 getJSON 函数中,您需要为您要引入的每个对象创建一个新对象,其中还包括一个空的“数据”数组(请参阅下面的“var 系列”)。
Then nest a few $.each
loops to parse and push the data into their necessary arrays, and populate the "name" of each object:
然后嵌套几个$.each
循环来解析数据并将其推送到所需的数组中,并填充每个对象的“名称”:
$.getJSON('http://exmaple.com/getdata.php?ID=' + id, function(data) {
$.each(data, function(key,value) {
var series = { data: []};
$.each(value, function(key,val) {
if (key == 'name') {
series.name = val;
}
else
{
$.each(val, function(key,val) {
var d = val.split(",");
var x = Date.UTC(d[0],d[1],d[2]);
series.data.push([x,d[3]]);
});
}
});
options.series.push(series);
});
After the above code, you need to instantiate the chart:
在上面的代码之后,你需要实例化图表:
var chart = new Highcharts.Chart(options);
And that should be it!
应该就是这样!
Hopefully somebody else finds this answer useful and doesn't need to beat themselves over the head for days trying to figure it out. :-)
希望其他人发现这个答案很有用,并且不需要花费数天时间试图弄清楚它。:-)
回答by Tamas Kalman
Since Javascript UTC method will return with an Integer, it's just better if you just pass the Unix Timestamp as an integer when you're generating the JSON on the serverside instead trying to pass a function (UTC.Date) in the JSON - that makes the entire JSON invalid!
由于 Javascript UTC 方法将返回一个整数,如果在服务器端生成 JSON 时将 Unix 时间戳作为整数传递而不是尝试在 JSON 中传递函数 (UTC.Date),那就更好了 - 这使得整个 JSON 无效!
So
所以
Instead of this
而不是这个
while ($item = mysql_fetch_assoc($result)) {
$name = $item['Item1'];
$date = str_replace("-",",",$item['Item2']);
$pos = $item['Item3'];
$arr = array("name"=>$name,"data"=>"[Date.UTC(".$date."), ".$pos." ],");
echo json_encode($arr);
}
Do this:
做这个:
while ($item = mysql_fetch_assoc($result)) {
$name = $item['Item1'];
$unix_date = date("Y-m-d", strtotime($item['Item2']));
$pos = $item['Item3'];
$arr = array("name"=>$name,"data"=>"[".($unix_date*1000).", ".$pos." ],");
echo json_encode($arr);
}
Please note we're multiplying the PHP unix timestamp by 1000 to make it JS compatible.
请注意,我们将 PHP unix 时间戳乘以 1000 以使其与 JS 兼容。
Reference: http://www.w3schools.com/jsref/jsref_utc.asp
回答by sicks
Just checked with some sample code for Highcharts, series
needs to be an array of JSON objects each containing {"name":"Item1","data":"[Date.UTC(2011,11,08), 4 ],"}
etc.
刚刚检查了 Highcharts 的一些示例代码,series
需要是一个 JSON 对象数组,每个对象都包含{"name":"Item1","data":"[Date.UTC(2011,11,08), 4 ],"}
等。
The main problem is your output from page2, is not an array.
主要问题是 page2 的输出不是数组。
You'll need to fix your $.each first, you need to push value
, not data
:
你需要先修复你的 $.each ,你需要 push value
,而不是data
:
$.each(data, function(key,value) {
options.series.push(value);
});
This will properly set each item in series to the full json object.
这会将系列中的每个项目正确设置为完整的 json 对象。
Then to fix the output:
然后修复输出:
$output = [];
while ($item = mysql_fetch_assoc($result)) {
$name = $item['Item1'];
$date = str_replace("-",",",$item['Item2']);
$pos = $item['Item3'];
//I don't think there's supposed to be a comma after this square bracket
$arr = array("name"=>$name,"data"=>"[Date.UTC(".$date."), ".$pos." ]");
array_push($output, json_encode($arr));
}
echo "[";
foreach($output as $val){
echo $val;
if($val != end($output)) echo ",";
}
echo "]";
And that should do it.
那应该这样做。
回答by Kunal Panchal
Checked in PHP5.5
已签入 PHP5.5
You can simply add this into the json with the data series
您可以简单地将其添加到带有数据系列的 json 中
$date = '31-12-2015 00:00:00';
$datetimeUTC = (strtotime($date) * 1000);
$data[] = [$datetimeUTC, (float) $value];
回答by Dimitri L.
I came across the problem of sending timestamps produced by mktime() because highcharts expects UTC time while PHP Timestamp is not UTC. The data could be shown on a wrong day in the chart, so you also have to consider the time zone.
我遇到了发送由 mktime() 生成的时间戳的问题,因为 highcharts 需要 UTC 时间,而 PHP Timestamp 不是 UTC。数据可能显示在图表中的错误日期,因此您还必须考虑时区。
function _convertToUTC($timeStamp) {
return (int)$timeStamp + (int)date('Z', $timeStamp);
}
Code Example would be:
代码示例将是:
$serie = array(
'name' => 'title',
'data' => array(
// multiply timestamp by 1000 to get milliseconds
array(_convertToUTC(mktime(0,0,0,1,1,2016)) * 1000, 15),
array(_convertToUTC(mktime(0,0,0,2,1,2016)) * 1000, 18),
array(_convertToUTC(mktime(0,0,0,3,1,2016)) * 1000, 13),
),
);
echo json_encode($serie);