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?
The documentation says why.
NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
the problem here is that you didn't understand the depth
parameter correctly
the depth of your test
array is 3 and so it will not be printed in the first two iterations and a null
value is returned
but in the 3rd iteration it gets printed because its depth is equal to the $depth
[i.e. 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With