tags:

views:

491

answers:

3

Scenario:

$x = json_decode( $x );
foreach ( $x as $item )
{
    $info[] = $item;  //ERROR
}

I am looping though a datafeed to get the data. I want to add items to a stdClass object in a loop. How would I do that? I'm not that familiar with stdobj's.

+4  A: 

If I understand you correctly, you should just be able to follow regular object syntax to get the result you want. Add the optional second parameter to json_decode set to true to get your json decoded as an associative array, as it seems as if this is the form that you're using it in.

$info = new stdClass();
$x = json_decode( $x, true );
foreach ( $x as $key => $val) { 
    $info->$key = $val;
}

As Ignas pointed out though, the results of json_decode() already come back as a stdClass object, so if you just used $x = json_decode($x), you wouldn't need $info at all... you'd already have $x as a stdClass object.

zombat
+2  A: 

If you expect the json_decode to return an array, you could do the following:

$x = json_decode( $x, true ); // returns associative array instead of object
$info = (object) $x;

More info and examples can be found here.

Pras
May I point out that you're casting an object to an object? That doesn't seem very useful.
deceze
Good catch! Fixed the code so that it returns an array instead of an object.
Pras
+1  A: 

SPL's ArrayObject let's you use the same syntax that generates an error in your example. This is provided you have the ability to use an ArrayObject instead of a stdClass.

chelmertz