Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_decode depth parameter doesn't work

Tags:

json

php

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?

like image 329
Sean Avatar asked Oct 15 '13 19:10

Sean


2 Answers

The documentation says why.

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

like image 132
Explosion Pills Avatar answered Oct 09 '22 13:10

Explosion Pills


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]

like image 42
Aditya Vikas Devarapalli Avatar answered Oct 09 '22 13:10

Aditya Vikas Devarapalli