I have this example code:
$array = array(
'GiamPy' => array(
'Age' => '18',
'Password' => array(
'password' => '1234',
'salt' => 'abcd',
'hash' => 'whirlpool'
),
'Something' => 'Else'
)
);
echo json_encode($array, JSON_PRETTY_PRINT);
I have seen in the PHP documentation that, since PHP 5.5.0 (thus recently), json_encode
allows a new parameter which is the depth.
The json_encode() function is used to encode a value to JSON format.
JsonEncoder and JsonDecoderA decoder is a function that takes a CharSequence and returns a Right with the decoded value or a Left with an error message. An encoder is a function that takes a value of type A and returns a CharSequence that represents the encoded value (JSON string).
The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
The option limits the depth that will be processed (d'uh). The depth of an array is measured by how deep it is nested. This is an array of depth 1:
array(
'foo',
'bar',
'baz'
)
This is an array of depth 2:
array(
array(
'foo'
),
array(
'bar'
),
array(
'baz'
)
)
// ------ depth ------>
If the input surpasses the maximum depth (by default 512), json_encode
will simply return false
.
Why you may use this is debatable, you may want to protect yourself from inadvertent infinite recursion or too much resource use. An array which is deeper than 512 levels probably has infinitely recursive references and cannot be serialised. But if you are sure your array is not infinitely recursive yet is deeper than 512, you may want to increase this limit explicitly. You may also want to lower the limit as a simple error catcher; say you expect the result to have a maximum depth but your input data may be somewhat unpredictable.
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