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

标签 php migration php-7.2 jsondecoder

The official doc说:

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);

但是只有最后一次打印才作为数组打印。

我理解错了吗?

最佳答案

检查function signature :

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 is JSON_OBJECT_AS_ARRAY that has the same effect as setting assoc to TRUE.

这意味着您可以将第四参数设置为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/

相关文章:

PHP Mysql自动报价?

php - 为什么 php 将空字节添加到私有(private)和 protected 属性名称?

php - PHP 7 中静默 "Declaration ... should be compatible"警告

php - 在 Symfony PHP 中重定向来自事件订阅者的响应

php - Magento 1.7.0.2 安装重定向循环 index.php/install

php - 从 php 调用 c

javascript - 单击按钮时将 twig 中的 javascript 变量传递给 php Controller

python - 使用 SQLAlchemy 删除和读取索引

git - ClearCase 到 Git 的迁移

database - migrator.net vs fluentmigrator vs migsharp