4

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
}
pjama
  • 3,014
  • 3
  • 26
  • 27

4 Answers4

6

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
}
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Ahh, Thanks. I knew it was something simple. The previous line was `$json = base64_decode($json);` So it would output a string. – pjama Mar 26 '11 at 18:27
1

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

The JSON-String itself is meaningless to foreach.

Raffael
  • 19,547
  • 15
  • 82
  • 160
1

Try using json_decode() first. It looks like your variable is json encoded, which means it's really just a string, and therefore not enumerable by foreach.

foreach(json_decode($json) as $obj) {
    // stuff
}
beeglebug
  • 3,522
  • 1
  • 23
  • 39
0

foreach(json_decode($json) as $obj) { // stuff }

It returns me a Warning like this : Invalid argument supplied for foreach(), although works.

My code is here:

function search_terms ( $json , $term ) 
        {
            if ( $json != null ){
                foreach ( $json as $item ) {// Recursive function
                    $this->search_terms ( $item, $term );
                }
            }else{

            }
        }
USSliberty
  • 65
  • 1
  • 6