2015-09-24 62 views
-1

我想從這個json_encode響應中獲得使用和它在php中的狀態。我該如何得到它?請求像json_encode(陣列( '在線'=> $狀態))如何從json_encode獲取數據?如何通過使用AJAX獲得答覆?

{"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

似乎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

0

可以使用json_decode(解碼JSON)函數,如下所示:

<?php 
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
(json_decode($json);  
?> 

另一個實施例(讀取特定對象) :「?如何通過使用AJAX來得到響應」

<?php 
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
$obj = json_decode($json); //read a specific object 
print $obj->{'a'}; // 1 
?> 

UPDATE我看你你的問題更新

  //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 

       } 
      });