Observe this little script:
$array = array(\'stuff\' => \'things\');
print_r($array);
//prints - Array ( [stuff] => things )
$arrayEncoded = json_encod
Why does PHP turn the JSON Object into a class?
Take a closer look at the output of the encoded JSON, I've extended the example the OP is giving a little bit:
$array = array(
'stuff' => 'things',
'things' => array(
'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
)
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}
The JSON format was derived from the same standard as JavaScript (ECMAScript Programming Language Standard) and if you would look at the format it looks like JavaScript. It is a JSON object ({}
= object) having a property "stuff" with value "things" and has a property "things" with it's value being an array of strings ([]
= array).
JSON (as JavaScript) doesn't know associative arrays only indexed arrays. So when JSON encoding a PHP associative array, this will result in a JSON string containing this array as an "object".
Now we're decoding the JSON again using json_decode($arrayEncoded)
. The decode function doesn't know where this JSON string originated from (a PHP array) so it is decoding into an unknown object, which is stdClass
in PHP. As you will see, the "things" array of strings WILL decode into an indexed PHP array.
Also see:
Thanks to https://www.randomlists.com/things for the 'things'
There is also a good PHP 4 json encode / decode library (that is even PHP 5 reverse compatible) written about in this blog post: Using json_encode() and json_decode() in PHP4 (Jun 2009).
The concrete code is by Michal Migurski and by Matt Knapp:
Take a closer look at the second parameter of json_decode($json, $assoc, $depth)
at https://secure.php.net/json_decode
tl;dr: JavaScript doesn't support associative arrays, therefore neither does JSON.
After all, it's JSON, not JSAAN. :)
So PHP has to convert your array into an object in order to encode into JSON.
Although, as mentioned, you could add a second parameter here to indicate you want an array returned:
$array = json_decode($json, true);
Many people might prefer to cast the results instead:
$array = (array)json_decode($json);
It might be more clear to read.
$arrayDecoded = json_decode($arrayEncoded, true);
gives you an array.