2013-11-25 111 views
1

我有一個json文件,我想用PHP顯示它的數據。我下面的代碼給我的錯誤,使用PHP獲取json數據

$json = file_get_contents('data.json'); 
$data = json_decode($json,true); 
$users = $data['devices']; 
foreach($users as $user) 
{ 
echo $user['id']; 
echo $user['user']; 
} 

當我更換$users = $data['user'];第三LOC那麼它顯示的一些數據與單個字母我不以何種順序知道。

Data.json文件包含以下數據

{ 
"user": 
    { 
    "id":"#03B7F72C1A522631", 
    "user":"[email protected]", 
    "password":"123", 
    "email":"[email protected]", 
    "name":"m", 
    "creationDate":1385048478, 
    "compression":true, 
    "imageProfile":"medium", 
    "videoProfile":"medium", 
    "blockAdvert":true, 
    "blockTracking":true, 
    "devices":[ 
     { 
     "id":"#13C73379A7CC2310", 
     "udid":"cGMtd2luNi4xLV", 
     "user":"[email protected]", 
     "creationDate":1385048478, 
     "status":"active", 
     }, 
     { 
     "id":"#FE729556EDD9910D", 
     "udid":"C1N1", 
     "user":"[email protected]", 
     "creationDate":1385291938, 
     "status":"active", 
     }] 
    }, 
"status": 
    { 
    "version":"0.9.5.0", 
    "command":"getuser", 
    "opf":"json", 
    "error":false, 
    "code":0 
    } 
} 

回答

3

我想你可能需要做顯示所有devices信息,你可以改變你的代碼:

$json = file_get_contents('data.json'); 
$data = json_decode($json,true); 

// change the variable name to devices which is clearer. 
$devices = $data['user']['devices']; 
foreach ($devices as $device) 
{ 
    echo $device['id']; 
    echo $device['user']; 
} 
+0

非常感謝你,現在它對我很好用:) – Arif

1

您沒有正確訪問您的JSON。你需要像這樣訪問它。

$yourVariable = $data['users']['devices']; 

試試看。

+0

OP寫'$數據= json_decode($ json的,真正的);'它返回一個數組,而不是目的。 –

+0

http://docs.php.net/json_decode該文檔說如果參數$ assoc爲true,它會將對象變成關聯數組。我很確定,如果我錯了,默認情況下這是錯誤的。 – ddelnano

+0

http://www.phpriot.com/manual/php/function.json-decode這個例子顯示如果$ assoc參數被省略,則默認返回一個對象。 – ddelnano

4

我相信你跳過了1個節點,嘗試:

$users = $data['user']['devices']; 
4

這應該工作;

$json = file_get_contents('data.json'); 
$data = json_decode($json,true); 
$users = $data['user']['devices']; 
foreach($users as $user) { 
    echo $user['id']; 
    echo $user['user']; 
} 

有一個前 '設備' 鍵