foreach循环与解码的json数据

时间:2015-06-26 11:20:25

标签: php html json foreach

我试图通过foreach循环显示来自JSON响应的数据。但是,如果我尝试,我会收到此错误:

  

为foreach()提供的参数无效

我放在foreach循环中的数据不为空或空,我检查过。

我的代码:

$json = file_get_contents($goodurl);
$the_data = json_decode($json, true);
$count = 0;
foreach($the_data->response as $video)
{
//case show results as text only
//echo $video->title;
$html.= "<p><div class='p2go_title'><a href='". $video->playbackUrl ."' target='_blank'>" . $video->title . "</a></div>";
$html.= "<div class='p2go_contributors'>By: ". $video->contributors ."</div>";
$html.= "<div class='p2go_views'>Views: ". $video->views ."</div></p>";

$count++;
}
return $html;

2 个答案:

答案 0 :(得分:2)

由于您要将json_decode设置为返回数组,因此请将其作为array访问,而不是object

$the_data = json_decode($json, true); // if you set 2nd paramater to true, it will return an array

foreach($the_data['response'] as $video)
{
   $html.= "<p><div class='p2go_title'><a href='". $video['playbackUrl']."' target='_blank'>" . $video['title'] . "</a></div>";
   $html.= "<div class='p2go_contributors'>By: ". $video['contributors'] ."</div>";
   $html.= "<div class='p2go_views'>Views: ". $video['views'] ."</div></p>";

 $count++;
}

答案 1 :(得分:1)

$the_data是数组。试试 -

foreach($the_data['response'] as $video)

json_decode($json, true);将返回一个数组。第二个参数仅用于此。

<强>更新

内部元素也需要作为数组加入 -

$html.= "<p><div class='p2go_title'><a href='". $video['playbackUrl'] ."' target='_blank'>" . $video['title'] . "</a></div>";
$html.= "<div class='p2go_contributors'>By: ". $video['contributors'] ."</div>";
$html.= "<div class='p2go_views'>Views: ". $video['views'] ."</div></p>";