2014-08-31 211 views
0

我試圖從下面的輸出中獲取用戶名和ID的值。無法解析json屬性

{ 
    "listusersresponse": { 
    "count": 1, 
    "user": [ 
     { 
     "id": "f01e8ea4-2da5-11e4-a846-726c7bbb864f", 
     "username": "admin", 
     "firstname": "admin", 
     "lastname": "test", 
     "created": "2014-08-26T20:52:24-0400", 
     "state": "enabled", 
     "account": "admin", 
     "accounttype": 1, 
     "domainid": "c091153a-2da5-11e4-a846-726c7bbb864f", 
     "accountid": "f01e7c02-2da5-11e4-a846-726c7bbb864f", 
     "iscallerchilddomain": false, 
     "isdefault": true 
     } 
    ] 
    } 
} 

這是我曾嘗試

$url = file_get_contents("http://URL/client/&response=json"); 

$data = json_decode($url); 

var_dump($data); 

foreach ($data as $value) { 
    echo $value->count; 
    } 

對於這個工作,我得到1

但是嘗試訪問 「用戶名」

foreach ($data as $value) { 
    echo $value->user->username; 
    } 

我得到以下時錯誤:注意:試圖在「文件名」中獲取非對象的屬性

回答

2

用戶是一個數組。

foreach ($data as $value) { 
    echo $value->user[0]->username; 
} 

不知道你的JSON的外觀與幾個用戶,它必須是這樣的話,我想:

foreach ($data as $value) { 
    foreach ($value->user as $user) { 
     echo $user->username; 
    } 
} 
+1

完美,謝謝! – Deano 2014-08-31 12:12:36