[英]Why is there json_decode($array, TRUE)?
I send a dictionary as JSON to a server. 我将字典作为JSON发送到服务器。 The dictionary contains only 1 key, that is an array of items:
字典只包含1个键,即一个项目数组:
header('Content-type: application/json');
$request = json_decode(file_get_contents('php://input'));
$array = json_decode($request['array']);
The value for key 'array' is an array, can't be an object. 键'array'的值是一个数组,不能是一个对象。
So, basically these two methods will return the same thing: 所以,基本上这两种方法将返回相同的东西:
$array = json_decode($request['array']);
$array = json_decode($request['array'], TRUE);
Am I right? 我对吗?
The only use for this method is when you want to convert an object into an array: 此方法的唯一用途是当您要将对象转换为数组时:
$array = json_decode($request['object'], TRUE);
Why would you ever want to do that? 你为什么要这样做?
I mean, I do understand that 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's a huge mind gap. 我的意思是,我确实知道可能有这方面的应用,但另一方面,我花了一整天的时间来消化这种思维方式,它仍然感觉有一个巨大的思维差距。
This little convenience messes up with the concrete way of parsing data and is just confusing to a newbie like me. 这种小小的便利与解析数据的具体方式相混淆,只会让像我这样的新手感到困惑。
There's a clear distinction between arrays and objects in Javascript/JSON. Javascript / JSON中的数组和对象之间有明显的区别。 Arrays do not have explicit indices but are numerically indexed, while objects are unsorted and have named properties.
数组没有显式索引,但是以数字方式编制索引,而对象未排序且具有命名属性。 By default
json_decode
honours this difference and decodes JSON arrays to PHP arrays and JSON objects to PHP objects (instances of stdClass
). 默认情况下,
json_decode
尊重这种差异,并将JSON数组解码为PHP数组,将JSON对象解码为PHP对象( stdClass
实例)。
However, PHP's arrays also happen to support associative indices; 但是,PHP的数组也恰好支持关联索引; so a JSON object could be decoded to either a PHP object or a PHP array.
所以JSON对象可以解码为PHP对象或 PHP数组。 You can choose which you prefer with that second parameter to
json_decode
. 您可以使用第二个参数选择您喜欢的
json_decode
。 There's no 100% clear 1:1 mapping between these two different languages here, so there's a preference instead. 这里两种不同语言之间没有100%明确的1:1映射,所以有一个偏好。
Why the true is there, 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));
?>
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)
}
简单如果您使用true,我将以数组格式显示,如果您不使用,将显示为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.