2

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.

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.