从 PHP 7.1.x 迁移到 PHP 7.2.x json_decode() 更改



>官方文档说:

现在使用 json_decode(( 函数选项 JSON_OBJECT_AS_ARRAY 如果第二个参数 (assoc( 为 NULL。以前 JSON_OBJECT_AS_ARRAY总是被忽视。

此代码 (AFAIK( 完成此更改和条件:

<?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 ]]] )

选项

JSON 解码选项的位掩码。目前有两个 支持的选项。第一个是允许JSON_BIGINT_AS_STRING将大整数转换为字符串而不是默认值的浮点数。 第二个选项是具有相同效果的JSON_OBJECT_AS_ARRAYassoc设置为TRUE

这意味着您可以将第四个参数设置为JSON_OBJECT_AS_ARRAY,即使您出于某种原因未将第二个参数设置为true,而是将其设置为null。但是这第四个参数的默认值是 0,这意味着如果只有第二个参数设置为null,则不会进行转换(从对象到数组(。

以下是显示差异的缩短演示:

$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 之后产生数组。

最新更新