Why does json_decode ($ array, TRUE) exist?

I am sending a JSON dictionary to the server. The dictionary only contains 1 key, which is an array of elements:

header('Content-type: application/json');

$request = json_decode(file_get_contents('php://input'));

$array = json_decode($request['array']);

      

The value for an "array" key is an array, cannot be an object.

So basically these two methods will return the same thing:

$array = json_decode($request['array']);

$array = json_decode($request['array'], TRUE);

      

I'm right?

The only use for this method is when you want to convert an object to an array:

$array = json_decode($request['object'], TRUE);

      

Why would you do this?

I mean, I understand there might be applications for this, but on the other hand, it took me a whole day to digest this way of thinking and it still feels like there is a huge gap in the mind.

This little convenience will mess up the particular way of analyzing the data and just confuse a newbie like me.

+3


source to share


3 answers


There's a clear distinction between arrays and objects in Javascript / JSON. Arrays do not have explicit indexes, but are numerically indexed, and objects are not sorted and have named properties. By default, json_decode

will distinguish this difference and decode JSON arrays to PHP arrays and JSON objects to PHP objects (instances stdClass

).



However, PHP arrays also support associative indexes; therefore JSON object can be decoded for either PHP object or PHP array. You can choose the one you prefer with this second parameter json_decode

. There is no 100% transparent 1: 1 mapping between these two different languages, so you prefer instead.

+5


source


Why there is truth, you can understand. See the following code below.

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

      



The output will be for the above code:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

      

0


source


Just If you use true I will show in array format and if you don't use it then it will show in

0


source







All Articles