Amit Ray Amit Ray - 4 months ago 13
JSON Question

Confusion with JSON_DECODE second param

I just created a small program to check JSON and JSON_FORCE_OBJECT

$tree = [
0 => array
(
'id' => 1,
'parent' => '0',
'name' => 'b',
'surname' => 'myfolder/b'
),

1 => array
(
'id' => 2,
'parent' => 1,
'name' => 'ignore',
'surname' => 'myfolder/ignore2'
),

2 => array
(
'id' => 3,
'parent' => 1,
'name' => 'ignore2',
'surname' => 'myfolder/ignore4'
)

];
var_dump($tree);
$try = json_encode($tree);//To print with key. Also if we decode we get result as object
//echo $try;
echo '<br />';
$try2 = json_decode($try,JSON_FORCE_OBJECT);
var_dump($try2);


$try2 is exactly equal to $tree an associative array.
Whereas if I remove
JSON_FORCE_OBJECT
from this line

$try2 = json_decode($try,JSON_FORCE_OBJECT);


I get an array with child object. Though
JSON_FORCE_OBJECT
is supposed to be used with json_encode but using it with json_decode, I get a surprising result. I am unable to understand whats going on inside?? I thought when I encode it and decode it I should get same result. But I got the same result only when I used
JSON_FORCE_OBJECT
. Can anyone please help why this happens?

Answer

According to the manual: http://php.net/manual/en/function.json-decode.php

json_decode returns an array of objects if you want to convert then in assoc array you should specify the second param which is a boolean

JSON_FORCE_OBJECT is an int with value 16... when this is passed as second param php cast/converts it to its bool equivalent which true.

To test the above stated behavior try:

var_dump((bool)1; (bool)2, (bool)16) 
//output  bool(true)  bool(true)  bool(true) . 
var_dump((bool)0)
//outputs bool(false)

So it's nothing to do with JSON_FORCE_OBJECT...even

json_decode($try,true);
json_decode($try,2);
json_decode($try,3);
json_decode($try,4);
json_decode($try,'someVar');
....
//should return your expected result (assoc array)

Similarly if you pass 0 as second param PHP will cast it into bool (which is false) and returns you an object

json_decode($try,0);
json_decode($try,false); 
json_decode($try,null)
json_decode($try)
...
//will return objects