2015-10-19 110 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"); 
}