Frank Thornton Frank Thornton - 2 months ago 6
JSON Question

Converting json_decode to an object

I get the following output with json_decode

Array
(
[0] => Array
(
[...] => ...
[...] => ...
)

[1] => Array
(
[...] => ...
[...] => ...
)


What I want to do is import this to a class so I can call and reference the data from memory.

From research I found this:
How to convert an array into an object using stdClass()

However, I am not sure if stdClass is the way I want to go?

Answer

Function definition from the PHP manual:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

Considering your JSON string [{"first_name":"Jason","last_name":"Pass", [...], you must be using json_decode with its second parameter set to TRUE.

That means that objects from the JSON string are returned as associative arrays. If you omit the second parameter (or use the default FALSE value), you will get:

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'first_name' => string 'Jason' (length=5)
      public 'last_name' => string 'Pass' (length=4)
      ...
  1 => 
    object(stdClass)[2]
      ...

This means objects from the JSON string are preserved as objects.

However, the array containing your objects will remain an array, because this is how it should be and you should not force it to be an object. There is no good reason to do that.

Comments