PHP's json_decode function has a "depth" parameter, where you can specify how deep it will recurse. But the following code:
test = array(
'name' => 'sean',
'dob' => '12-20',
'parents' => array(
'father' => 'tommy',
'mother' => 'darcy'
)
);
foreach(range(1, 3) as $depth) {
echo "-----------------\n depth: $depth\n";
print_r(json_decode(json_encode($test), true, $depth));
}
Produces this output:
-----------------
depth: 1
-----------------
depth: 2
-----------------
depth: 3
Array
(
[name] => sean
[dob] => 12-20
[parents] => Array
(
[father] => tommy
[mother] => darcy
)
)
What I would expect is a depth of 1 to show "name" and "dob", and a depth of 2 to show the parents, also. I don't get why a depth of 1 or 2 displays nothing at all.
Can anyone explain to me what I'm not understanding?
In addition to @Explosion Pills answer, you expect
json_decode
to work asjson_encode
should.According to documentation you can now specify your own limit, to encode arrays/objects. Which simply means that it will skip going deeper than specified level.
For
json_decode
it's different - it always try to parse whole JSON string, because it simply can't stop, and skip deeper parts without parsing the whole string. This is why depth limit causes the function to return NULL in this cases.json_encode
can stop and skip deeper parts, as the data structure is already defined in the memory.Notice that
$depth
forjson_encode
was added for PHP version 5.5.0 (json_decode
has it since 5.3.0). Check changelog here.the problem here is that you didn't understand the
depth
parameter correctlythe depth of your
test
array is 3 and so it will not be printed in the first two iterations and anull
value is returnedbut in the 3rd iteration it gets printed because its depth is equal to the
$depth
[i.e. 3]The documentation says why.