2015-10-19 301 views
0

我在解碼JSON數據時遇到問題。 有人不明白爲什麼變量$clanid沒有設置?json_decode無法正常工作

這是代碼:

$url = "http://185.112.249.77:9999/Api/Search?search=&level=1&min=1&max=50&points=48000"; 
$jsondata = file_get_contents($url); 
$data = json_decode($jsondata, true); 

foreach ($data->clanList as $clan) { 

$clanid = $clan->id; 
echo $clan->id; 
} 

在此先感謝您的幫助。

+1

Protip:'var_dump($ data);'。這是你所期望的嗎? –

+2

爲什麼傳遞'true'並不知道它在做什麼? – AbraCadaver

+1

RTFM:http://php.net/json_decode第二個參數:'當TRUE時,返回的對象將被轉換爲關聯數組。你迫使PHP返回一個數組,然後嘗試將該數組視爲一個對象。 –

回答

2

json_decode的第二個參數需要一個布爾值。如果設置爲true,則強制輸出爲數組。它默認爲false,這將解碼爲一個對象,這就是你需要

$data = json_decode($jsondata); //removed boolean arg 
+0

你說得對。 json_decode($ jsondata,true);將只返回一個數組而不是對象 –

+0

說明:因爲第二個參數設置了json將被轉換爲關聯數組而不是對象。 – Slowmove

2

既然你與真正的第二個參數調用json_decode,你的JSON對象是decodec到一個關聯數組,而不是一個對象,因此在foreach應

foreach($data['clanList'] as $clan 

看一看php manual

assoc命令

當TRUE時,返回的對象將被轉換爲關聯數組。

1

您試圖檢索爲對象。它不可能因爲你的解碼第二個參數表示json輸出在關聯數組中。請按照以下代碼

<?php 
//get the result from the url by using file_get_contents or curl 
    $jsondata = file_get_contents("http://185.112.249.77:9999/Api/Search?search=&level=1&min=1&max=50&points=48000"); 
//decode the json in associative array by putting true as second parameter 
    $data = json_decode($jsondata, true); 
//fixed array is chosen, clanList is fixed so stored clanList in $in 
    $in=$data['clanList']; 
//for each element of clanList as key=>value nothing but "element":"value" 
//for subarray in clanList use another foreach 
    foreach ($in as $key=>$value) { 
//to fetch value of element for each key   
    $clanid = $in[$key]['id']; 
    echo $clanid; 
    } 
    ?> 
0

您有一個即時錯誤和一個潛在錯誤。

json_decode()與第二個參數true將返回一個關聯數組(如果可以的話)。因此你的foreach(和其他引用)應該使用數組索引而不是對象字段。

添加true似乎有意爲之,因此我假設您希望將數據用作關聯數組而不是對象。你當然可以刪除參數true

由於您有外部數據源,您可能仍然會收到錯誤。例如json_decode()也可以在無效的JSON上返回false。

如果您使用的是php 5.5,則可以使用json_last_error_msg來檢索郵件。否則,你可以回到json_last_error

正確的,(大部分)防止出錯的代碼是這樣:

$url = "http://185.112.249.77:9999/Api/Search?search=&level=1&min=1&max=50&points=48000"; 
$jsondata = file_get_contents($url); 
$data = json_decode($jsondata, true); 
if($data === false) { // check for JSON errors as well. 
    die(json_last_error()); 
} 

foreach ($data['clanList'] as $clan) { // use array syntax here. 
    $clanid = $clan['id']; // Use array syntax here. 
    echo $clanid; 
} 

編輯:補充說明有關也可能刪除true按照其他建議

+0

正確的方法是使用true來轉換爲數組。因爲file_get_contents無法將結果轉換爲對象。但如果使用cURL而不是file_get_contents,則可以將所有對象作爲對象處理:$ clan-> id –

0

首先應該檢查JSON返回並提取它。問題是當json被解碼的時候會變成0,1,2,3等,你將無法獲得clanList。爲此,您需要使用array_values

$url = "http://185.112.249.77:9999/Api/Search?search=&level=1&min=1&max=50&points=48000"; 
$jsondata = file_get_contents($url); 
$data = json_decode($jsondata, true); 
$get_indexes = array_values($data); 

if ($jsondata) { 
    foreach ($get_indexes as $clan) { 
    $clanid = $data[$clan]['id']; 
    echo $clanid; 
    } 
} else { 
exit("failed to load stream"); 
}