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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With