【问题标题】:Migrating from PHP 7.1.x to PHP 7.2.x json_decode() change从 PHP 7.1.x 迁移到 PHP 7.2.x json_decode() 更改
【发布时间】:2018-05-24 19:30:52
【问题描述】:

The official doc 说:

现在使用 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);

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

我理解错了吗?

【问题讨论】:

    标签: php migration php-7.2 jsondecoder


    【解决方案1】:

    查看function signature

    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

    这意味着你可以将fourth参数设置为JSON_OBJECT_AS_ARRAY,即使你没有将second参数设置为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 之后产生数组。

    【讨论】:

    • 非常感谢。 “JSON_OBJECT_AS_ARRAY,现在在第二个参数 (assoc) 为 NULL 时使用”。但是写得不好。可能会更好。
    • 是的,官方指南上写的最糟糕的描述方式!!
    • 谁会通过null 获得“bool $assoc = FALSE”?它是一个布尔字段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2018-08-10
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    相关资源
    最近更新 更多