Sem Abraham
Sem Abraham

Reputation: 151

foreach loop with decoded json data

I'm trying to get data from a JSON response to be displayed using a foreach loop. However if I try that I get this error:

Invalid argument supplied for foreach()

The data I put in the foreach loop isn't null or empty, I checked that.

My code:

$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;

Upvotes: 1

Views: 246

Answers (2)

Muhammet
Muhammet

Reputation: 3308

Since you are setting json_decode to return an array, access it as an array, not an 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++;
}

Upvotes: 2

Sougata Bose
Sougata Bose

Reputation: 31739

$the_data is array. Try with -

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

json_decode($json, true); will return an array. The second parameter is used for this only.

Update

The inner elements also be needed to be accesed as array -

$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>";

Upvotes: 1

Related Questions