php - 从 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);
但是只有最后一个打印,打印为数组。
我理解错了吗?
解决方案
检查函数签名:
mixed json_decode ( string $json [, bool $assoc = FALSE
[, int $depth = 512 [, int $options = 0 ]]] )
选项
JSON 解码选项的位掩码。目前有两个受支持的选项。第一个是
JSON_BIGINT_AS_STRING
允许将大整数转换为字符串而不是默认的浮点数。第二个选项与设置为JSON_OBJECT_AS_ARRAY
具有相同的效果assoc
TRUE
。
这意味着即使由于某种原因没有将第二个参数设置为,您也可以将第四个参数设置为,而是将其设置为。但是这第四个参数的默认值为 0,这意味着如果仅将第二个参数设置为 ,则不会进行任何转换(从对象到数组)。JSON_OBJECT_AS_ARRAY
true
null
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 之后产生数组。
推荐阅读
- java - 使用 Java FileSystems 删除 zip 中的多个文件
- java - 如何获得 int 分数以查看我的第二个活动
- go - 如何按顺序处理从某个用户到特定端点的并发请求
- reactjs - 删除 Redux-ORM 模型实例时出错(多对多)
- gps - 在这种 scrnaroo 中无法校准连接到车辆的磁力计,如图 8 校准
- database - MongoDB 排序操作的奇怪行为
- python-3.x - 从 sys.path 中删除无效引用
- ios - 如何在 RxSwift 中使用 tableView 的数据源(numberOfRowsInSection)?
- javascript - JavaScript 反向匹配
- angular - Spring Boot 项目中的多角度应用程序