php - 以 json 对象形式传递时间戳值以填充流程图

标签 php javascript jquery json flot

我试图通过从 MongoDb 查询来传递不同时间戳的值,然后以 JSON 的形式将它们传递给客户端。

然后客户端将读取 php 脚本返回的 JSON 对象,并在此基础上填充流程图。

我无法做到这一点,并且有以下两个疑问/疑问:

A.在php返回的JSON对象中,应该如何构造JSON对象?

目前,通过以下代码,生成的 JSON 如下:

[{"1371859200000":65},{"1371860100000":63},{"1371861000000":48},{"1371861900000":47},{"1371862800000":41},{"1371863700000":19},{"1371864600000":35}]

上面的说法对吗? 或者数据应该类似于: [["1371859200000":65],["137186​​0100000":63], ....]

他们两个有什么区别? (上面使用'['代替了大括号)

B. 在 PHP 中,strtotime 返回 int。但是,当我回显 JSON 对象时,生成的时间戳类似于“1371859200000”(即字符串),而不是 1371859200000(即 int)。为什么这样 ? 我必须填充图表,并且时间戳必须以 int(而不是字符串)形式出现才能填充图表。

以下是我的 PHP 代码(不是全部代码):

$date = 2;
$tsc = 15;
$result = array();
for ($hour = 0; $hour  < 24; $hour++) {
    for ($min_lower = 0; $min_lower <= 60-$tsc; $min_lower += $tsc) {
        // Query MongoDB.
        $query = array( "date" => $date, "hour" => $hour, "minutes" => array( '$gte' => $min_lower, "\$lt" => $min_lower+$tsc ) );
        $count = $coll->find($query)->count();
        $time = strtotime("2013-06-".strval($date)." ".strval($hour).":".strval($min_lower).":".strval(0)." UTC") * 1000;
        $data = array($time => $count);
        // Push this smaller array into the main array. Is this the correct way ?
        array_push($result, $data);
    }
}
echo json_encode($result);

以下是我的 javascript/jquery 代码:

var options = {
    lines: {
        show: true
    },
    points: {
        show: true
    },
    xaxis: {
        mode : "time",
        timeformat: "%m/%d/%y"
     }
};

$("button.fetch").click(function () {
    var button = $(this);
    var dataurl = "MY URL";// Here the URL comes.

    function onDataReceived(series) {
        data.push(series);
        $.plot("#placeholder", series, options);
    }
    $.ajax({
        url: dataurl,
        type: "GET",
        dataType: "json",
        success: onDataReceived
    });
 })

最佳答案

A. [[key: value]] 不是有效的 JavaScript 或 JSON 语法。您只能使用对象的键值对,即大括号语法。

B. 同样,对象键只能是字符串,不能是数字。 {123: "value"} 不是有效的 JSON 语法,它必须是 {"123": "value"}

两种可能的解决方案是

  1. 只需在JS端将key转换为数字即可;你可能可以相信它们永远都是数字
  2. 以不同方式表示数据,例如 [{"ts": 13456000, "count": 65}],因为值可以是数字,但键不能。

关于php - 以 json 对象形式传递时间戳值以填充流程图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16885829/

相关文章:

java - 相当于 php json_encode 的 Java 是什么

php - 正则表达式以匹配 PHP 中 HTML 正文的内容

php - 如何在codeigniter中将form标签转换为form_open

javascript - 谷歌分析 API Javascript : 403 Forbidden Error

javascript - XHR 抛出无法捕获的错误

javascript - 我可以通过 Promise 的解析/拒绝来控制函数的流程吗?

php - 任何特定国家/地区接下来的三个假期 - MySQL 还是 API?

javascript - jquery 1.8.3 实时点击事件更改为点击

javascript - jquery $(window).height() 未实现

jquery - 隐藏表格列的溢出影响了可容纳脚的列隐藏