Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach through JSONArray in PHP

Tags:

json

php

I'm getting this error:

Warning: Invalid argument supplied for foreach() in [page].php on line 49

This is an echo of the $json variable: [{"d":"2011-03-26","q":1,"t":1060},{"d":"2011-03-26","q":2,"t":1060},{"d":"2011-03-26","q":1,"t":1060}]

And I'm trying to iterate through like so:

foreach($json as $obj) { // <--THIS IS LINE 49
    // Stuff
}
like image 477
pjama Avatar asked Feb 25 '23 17:02

pjama


2 Answers

Just a guess:

Your $json variable is a string. You'll need to convert it to an object using json_decode to iterate through the object:

$json_obj = json_decode( $json );
foreach( $json_obj as $obj )
{
  //stuff
}
like image 185
zzzzBov Avatar answered Mar 02 '23 22:03

zzzzBov


you have to decode the json before you can iterate it.

The JSON-String itself is meaningless to foreach.

like image 37
Raffael Avatar answered Mar 02 '23 20:03

Raffael