我希望从这个json_encode响应中获得它在php中的使用和状态。我怎么得到它?请求像json_encode(array('online'=> $ status))
{"online":[{"user":"1004","status":"Unmonitored"},
{"user":"1005","status":"Unmonitored"},
{"user":"1006","status":"Unmonitored"},
{"user":"2501","status":"Unmonitored"},
{"user":"2502","status":"Unmonitored"},
{"user":"2503","status":"Unmonitored"},
{"user":"2504","status":"Unmonitored"}]}
答案 0 :(得分:0)
您可以使用json_decode()函数解码JSON,如下所示:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
(json_decode($json);
?>
另一个例子(读取特定对象):
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$obj = json_decode($json); //read a specific object
print $obj->{'a'}; // 1
?>
更新我看到您将问题更新为“如何使用AJAX获取响应?”
//start ajax request
$.ajax({
url: "data.json",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//do what you want to do here
}
});
答案 1 :(得分:0)
PHP 5.4提供了JSON_PRETTY_PRINT
选项,可用于json_encode()
调用。
http://php.net/manual/en/function.json-encode.php
<?php
$json_string = json_encode($data, JSON_PRETTY_PRINT);
&GT;
答案 2 :(得分:0)
似乎json_decode
是您正在寻找的功能。
<?php
$data = '{"online":[
{"user":"1004","status":"Unmonitored"},
{"user":"1005","status":"Unmonitored"},
{"user":"1006","status":"Unmonitored"},
{"user":"2501","status":"Unmonitored"},
{"user":"2502","status":"Unmonitored"},
{"user":"2503","status":"Unmonitored"},
{"user":"2504","status":"Unmonitored"}
]}';
// json_decode produces stdClass object
$decoded_std = json_decode($data);
var_dump($decoded_std->online[0]->status); // "Unmonitored"
// json_decode produces associative array
$decoded_array = json_decode($data, true); // note the second param
var_dump($decoded_array['online'][0]['status']); // "Unmonitored"
在此处查看托管的工作示例http://ideone.com/xaCx4E。