The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is NULL. Previously, JSON_OBJECT_AS_ARRAY was always ignored.
此代码(据我所知)完成了此更改和条件:
<?php
$an_object = new StdClass();
$an_object->some_atrribute = "value 1";
$an_object->other_atrribute = "value 2";
//an object
print_r($an_object);
$encoded = json_encode($an_object);
//here (null is passed in the second parameter)
$output = json_decode($encoded,null,512);
//using 7.2 should be array, however it is an object
print_r($output);
//array
$output = json_decode($encoded,true);
print_r($output);
但是只有最后一次打印才作为数组打印。
我理解错了吗?
最佳答案
mixed json_decode ( string $json [, bool $assoc = FALSE
[, int $depth = 512 [, int $options = 0 ]]] )
options
Bitmask of JSON decode options. Currently there are two supported options. The first is
JSON_BIGINT_AS_STRING
that allows casting big integers to string instead of floats which is the default. The second option isJSON_OBJECT_AS_ARRAY
that has the same effect as settingassoc
toTRUE
.
这意味着您可以将第四参数设置为JSON_OBJECT_AS_ARRAY
,即使您没有将第二参数设置为true
出于某种原因,但将其设置为 null
。但第四个参数的默认值为 0,这意味着如果仅将第二个参数设置为 null
,则不会进行转换(从对象到数组)。
这是the shortened demo显示差异:
$an_object = new StdClass();
$an_object->attr = 'value';
$encoded = json_encode($an_object);
print_r( json_decode($encoded, true, 512, JSON_OBJECT_AS_ARRAY) );
print_r( json_decode($encoded, false, 512, JSON_OBJECT_AS_ARRAY) );
print_r( json_decode($encoded, null, 512, JSON_OBJECT_AS_ARRAY) );
在这里,您将看到作为所有 PHP 版本中第一个和第二个解码操作的结果打印的数组和对象。但从 PHP 7.2.0 开始,第三个操作才会生成数组。
关于php - 从 PHP 7.1.x 迁移到 PHP 7.2.x json_decode() 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50516874/