2013-10-16 108 views
4

我試圖從獲得的JSON獲取單個值導致試圖獲取JSON結果

{ 
    "_total": 1, 
    "values": [{ 
    "id": 123456, 
    "name": "Example Technologies " 
    }] 
} 

現在,我需要得到_total值。對於我使用

echo $res->_total; 

這給了我 Notice: Trying to get property of non-object 如果我嘗試像 echo $res['_total']; 給我

Warning: Illegal string offset '_total' 

那麼,以什麼方式,我可以得到_total值。

請幫助我。提前致謝!

+0

爲了澄清這一點你$ res只是包含一個字符串值,這恰好是在JSON格式。這解釋了你所得到的錯誤。 – bouscher

+0

PHP不直接與JSON字符串..你需要json_decode()它們以便有php對象/數組並且使用它。 – Svetoslav

回答

1

假設數據是

$data = '{"category_id":"10","username":"agent1","password":"82d1b085f2868f7834ebe1fe7a2c3aad:fG"}'; 

和你想獲得特定參數,然後

$obj = json_decode($data); 

after 
$obj->{'category_id'} , $obj->{'username'} , $obj->{'password'} 

可能是這樣的幫助你!

+0

但數據是'{ 「_Total」:1, 「值」:[{ 「ID」:123456, 「名」: 「示例技術」 }] }' - 那麼,爲什麼假設別的東西嗎? – davidkonrad

2

這樣做:

$obj = json_decode($res); 
echo $obj->_total; 

您需要的JSON數據進行解碼。

1

看來你沒有json_decode()這個JSON字符串,或者$res不是json_decode()的結果。

例子:

$json = '{ 
    "_total": 1, 
    "values": [{ 
    "id": 123456, 
    "name": "Example Technologies " 
    }] 
}'; 

$res = json_decode($json); 

echo $res->_total; 
1

您將需要通過運行字符串json_decode第一http://uk3.php.net/json_decode 它會返回一個數組。

+0

'json_decode()'默認返回一個對象。您必須將第二個參數作爲「TRUE」傳遞才能返回數組。 –

0

這裏是你的字符串,

$data = '{ "_total": 1, "values": [{ "id": 123456, "name": "Example Technologies " }] }'; 
$test = (array)json_decode($data); 
echo '<pre>'; 
print_r(objectToArray($test)); 
die; 

功能在這裏

function objectToArray($d) { 
     if (is_object($d)) { 
      // Gets the properties of the given object 
      // with get_object_vars function 
      $d = get_object_vars($d); 
     } 

     if (is_array($d)) { 
      /* 
      * Return array converted to object 
      * Using __FUNCTION__ (Magic constant) 
      * for recursive call 
      */ 
      return array_map(__FUNCTION__, $d); 
     } 
     else { 
      // Return array 
      return $d; 
     } 
    } 

可能是它的幫助你!