PHP stdClass question

Scenario:

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

      

I am looping over data to get data. I want to add items to stdClass object in a loop. How should I do it? I am not familiar with stdobj's.

+2


source to share


3 answers


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

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

      



More information and examples can be found here .

+5


source


If you get it right, you should just follow the regular syntax of the object to get the desired result. Add an optional second parameter to json_decode

, set to true

, so that your json is decoded as an associative array as it appears to be the form you are using it in.

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

      



As Ignas pointed out, the results are json_decode()

already being returned as a stdClass object, so if you just used it $x = json_decode($x)

, you won't need it $info

at all ... you will already have it $x

as a stdClass object.

+4


source


SPL

ArrayObject

allows you to use the same syntax that generates the error in your example. This is ensured by what you can use ArrayObject

instead stdClass

.

+1


source







All Articles