PHP json_decode depth parameter not working

The PHP function json_decode has a depth parameter, where you can specify how deep it will repeat. 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 conclusion:

 ----------------- depth: 1 ----------------- depth: 2 ----------------- depth: 3 Array ( [name] => sean [dob] => 12-20 [parents] => Array ( [father] => tommy [mother] => darcy ) ) 

What I expect is depth 1 to show "name" and "ext", and depth 2 to show parents, too. I do not understand why a depth of 1 or 2 does not display anything at all.

Can someone explain to me what I don't understand?

+6
source share
3 answers

The documentation says why.

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

+8
source

the problem is that you did not correctly understand the depth parameter

the depth of your test array is 3 and therefore will not be printed in the first two iterations and null returned

but at the third iteration it prints because its depth is $depth [i.e. 3]

+4
source

In addition to @Explosion Pills answers, you expect json_decode to work like json_encode .

According to the documentation, you can specify your limit to encode arrays / objects. It just means that it will skip deeper than the specified level.

For json_decode it is different - it always tries to parse a whole JSON string, because it simply cannot stop and skip the deeper parts without parsing the entire string. This is why the depth limit causes the function to return NULL in this case.

json_encode can stop and skip deeper parts as the data structure is already defined in memory.

Note that $depth for json_encode was added for PHP version 5.5.0 ( json_decode has it since 5.3.0). Check out the change log here .

+2
source

Source: https://habr.com/ru/post/1261426/


All Articles