首页 > 解决方案 > 从 PHP 7.1.x 迁移到 PHP 7.2.x json_decode() 更改

问题描述

官方文档说:

如果第二个参数 (assoc) 为 NULL,则现在使用 json_decode() 函数选项 JSON_OBJECT_AS_ARRAY。以前,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);

但是只有最后一个打印,打印为数组。

我理解错了吗?

标签: phpmigrationphp-7.2jsondecoder

解决方案


检查函数签名

mixed json_decode ( string $json [, bool $assoc = FALSE 
  [, int $depth = 512 [, int $options = 0 ]]] )

选项

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

这意味着即使由于某种原因没有将第二个参数设置为,您也可以将第四个参数设置为,而是将其设置为。但是这第四个参数的默认值为 0,这意味着如果仅将第二个参数设置为 ,则不会进行任何转换(从对象到数组)。JSON_OBJECT_AS_ARRAYtruenullnull

这是显示差异的缩短演示:

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


推荐阅读