我意识到有相当多的这种性质的问题,但我没有能够解决我的问题使用其他帖子,所以我希望有人在这里可能能够帮助我。
我有一个对象,我从雅虎本地搜索API返回。我已经将结果传递到json_decode()
,并保存到$yahoo_json_decoded
。我可以使用for循环从结果中获取数据,并执行以下操作:
echo 'Name: ' . $yahoo_json_decoded->ResultSet->Result[$i]->Title . '<br />' ;
但我似乎不能使每一个工作:
foreach($yahoo_json_decoded->ResultSet as $res=>$variable)
{
$listingID = $yahoo_json_decoded->ResultSet[$res]->id ;
echo $listingID;
}
我可以只是循环数据并继续,但我真的想了解为什么foreach
不起作用。
Thanks (show mercy)
柯克基于您所说的$yahoo_json_decoded->ResultSet->Result[$i]->Title
:
foreach($yahoo_json_decoded->ResultSet->Result as $index => $result)
{
$listingID = $result->id ;
echo $listingID;
}
两个循环之间的文字差异
代码片段中的for
循环遍历数组 $yahoo_json_decoded->ResultSet->Result
,而foreach
循环遍历对象 $yahoo_json_decoded->ResultSet
。
换句话说,在for
循环中,你是在数组元素上迭代,而在foreach
循环中,你实际上是在对象属性上迭代。
差异的演示
例如,给定这个对象:
$json = json_encode(array('result'=>array('apple','orange','lemon')));
$obj = json_decode($json);
考虑以下循环的区别:
for ($i=0; $i < count($obj->result); $i++) :
echo $i.' - '.$obj->result[$i].' ';
endfor;
和这个循环:
foreach ($obj as $key=>$val) :
echo $key.' - ';
var_dump($val);
endforeach;
第一个循环的输出是:
0 - apple 1 - orange 2 - lemon
而第二个的输出将是:
result - array(3) { [0]=> string(5) "apple" [1]=> string(6) "orange" [2]=> string(5) "lemon" }
查看动作差异
据我所知,你应该做的是
foreach($yahoo_json_decoded->ResultSet->Result as $key => $val) //(...)
你在foreach循环中缺少了一层数据结构
foreach($yahoo_json_decoded->ResultSet->Result as $res=>$variable)
{
$listingID = $variable->id ;
echo $listingID;
}
和for循环
for ($i = 0; $i <10; $i++)
$yahoo_json_decoded->ResultSet->Result[$i]->Title
因此,$i = $res
$variable = $yahoo_json_decoded->ResultSet->Result[$i]