Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top