我有从数据库中返回的PHP代码,
[
{
"Time": "2012-11-27 16:10:35",
"NumPlayers": "1"
},
{
"Time": "2012-11-27 16:24:55",
"NumPlayers": "1"
},
{
"Time": "2012-11-27 16:25:37",
"NumPlayers": "2"
},
{
"Time": "2012-11-27 16:29:33",
"NumPlayers": "2"
时间是MySQL时间戳。我需要使用这种格式与Highcharts javascript图表一起使用。
data: [
[Date.UTC(1970, 9, 9), 0 ],
[Date.UTC(1970, 9, 14), 0.15],
[Date.UTC(1970, 10, 28), 0.35],
[Date.UTC(1970, 11, 12), 0.46],
我无法弄清楚如何遍历MySQL结果并将时间戳转换为javascript Date.UTC对象。我需要将NumPlayers值放在Date.UTC对象之后,并以下面的格式输出。我是一个PHP和javascript noob:\
看起来应该是这样的:
data: [
[Date.UTC(2012, 11, 27, 16, 10, 35), 1],
[Date.UTC(2012, 11, 27, 16, 24, 55), 1],
[Date.UTC(2012, 11, 27, 16, 25, 37), 2],
[Date.UTC(2012, 11, 27, 16, 29, 33), 2],
答案 0 :(得分:2)
您应该意识到Date.UTC(2012, 11, 27, 16, 10, 35)
只返回自纪元(1356624635000
)以来的毫秒数。因此,您可以将对象转换为UNIX时间戳(因为JS使用毫秒时间戳,因此PHP的工作时间为1000秒)。
<强> Sample Code 强>
$data = '[{"Time": "2012-11-27 16:10:35", "NumPlayers": "1"}, {"Time": "2012-11-27 16:24:55", "NumPlayers": "1"}]';
// Make sure date is parsed as UTC
date_default_timezone_set("UTC");
// Convert items into the desired format
$mapper = function($item) {
return array(strtotime($item->Time)*1000, $item->NumPlayers);
}
echo json_encode(array_map($mapper, json_decode($data)));
<强>输出强>
[[1354032635000,"1"],[1354033495000,"1"]]
答案 1 :(得分:1)
您似乎从数据库中直接获取JSON,您可以随时将其转换为数组:
$data = '[{"Time": "2012-11-27 16:10:35", "NumPlayers": "1"}, {"Time": "2012-11-27 16:24:55", "NumPlayers": "1"}]';
$arrayData = json_decode($data, true);
之后,您可以简单地遍历数组并以您需要的JS格式打印出数组的内容。这样的事情:
echo 'data: [' . PHP_EOL;
foreach ($arrayData as $item) {
echo '[Date.UTC(';
$tmp = preg_split( '/(-| |\:)/', $item['Time'] );
echo implode(', ', $tmp);
echo '), ' . $item['NumPlayers'] . '],';
echo PHP_EOL;
}
echo PHP_EOL . '];';
答案 2 :(得分:1)
您可以split使用/[^\d]+/g
var finalData = [], numbers=/[^\d]+/g, item, dateParts, newDate;
for (var i=0, l=data.length; i<l; i++) {
item = data[i];
dateParts = item.Time.split(numbers);
newDate = Date.UTC.apply(Date, dateParts);
finalData.push([newDate, item.NumPlayers]);
}
另请参阅:MDN's documentation on JavaScript regular expressions(/[^\d]/g
是正则表达式。)
答案 3 :(得分:1)
向Highcharts提供数据的最佳方式是从数据库中获取数据,这样您就不必在客户端进行数据。
要做到这一点,您只需将query
更改为以下内容。
<强>后端强>
$query = "SELECT UNIX_TIMESTAMP(date) * 1000 AS 'date', value FROM ...";
然后将结果发送到前端:
echo json_encode($result);
<强>前端强>
要在前端获得结果,这个案例使用jQuery并假设url
是你的网址:
$.getJSON(url, function(json) {
// decode json
var data = $.parseJSON(json);
// Then you just have to pass it to your series
});
或者更好,以UTC格式存储日期值。
答案 4 :(得分:0)
var php_data = [
{
"Time": "2012-11-27 16:10:35",
"NumPlayers": "1"
},
{
"Time": "2012-11-27 16:24:55",
"NumPlayers": "1"
}
];
var length = php_data.length;
hc_data = [];
for(var i = 0; i< length; i++){
php_date = new Date(php_data[i]["Time"]);
hc_data.push(
[
Date.UTC(
php_date.getFullYear(),
php_date.getMonth() + 1,
php_date.getDate()
),
php_data[i]["NumPlayers"]
]
);
}
// hc_data is your Array