【PHP】json_decode的第二个参数是什么意思

json_decode() 函数的第二个参数 $associative 是一个布尔值,用于控制 JSON 对象在 PHP 中的解码方式。当将其设置为 true 时,JSON 对象将被解码为关联数组;当设置为 false 时,JSON 对象将被解码为 stdClass 对象。默认值为 false

语法:

php 复制代码
function json_decode ($json, $associative = false, $depth = 512, $flags = 0) {}

以下是 json_decode() 函数的两种解码方式的示例:

  1. $associative 设置为 true 时,JSON 对象将被解码为关联数组:

    php 复制代码
    <?php
    $json = '{"name": "John", "age": 30, "city": "New York"}';
    
    $decoded = json_decode($json, true);
    
    print_r($decoded); // 输出:Array ( [name] => John [age] => 30 [city] => New York )
    ?>
  2. $associative 设置为 false 时(默认值),JSON 对象将被解码为 stdClass 对象:

    php 复制代码
    <?php
    $json = '{"name": "John", "age": 30, "city": "New York"}';
    
    $decoded = json_decode($json);
    
    print_r($decoded); // 输出:stdClass Object ( [name] => John [age] => 30 [city] => New York )
    ?>

在这两个示例中,我们使用 json_decode() 函数解码 JSON 字符串。

第一个示例中,我们将 $associative 参数设置为 true,以便将 JSON 对象解码为关联数组。

第二个示例中,我们将 $associative 参数设置为默认值 false,以便将 JSON 对象解码为 stdClass 对象。

相关推荐
cici158743 小时前
基于C#的智能仓储上位机系统实现方案
开发语言·c#
-Try hard-3 小时前
线程间通信 | 避免资源竞争、实现同步通信
linux·开发语言·信息与通信
楼田莉子3 小时前
C++并发库介绍(上)
开发语言·c++·学习
Nightmare0043 小时前
切换conda环境的时候输出zstandard could not be imported. Running without .conda support.
开发语言·python·conda
weixin_395448913 小时前
build_fsd_luyan_from_rm——注释
开发语言·windows·python
lsx2024063 小时前
NumPy 算术函数
开发语言
程序员南飞3 小时前
算法笔试-求一个字符串的所有子串
java·开发语言·数据结构·python·算法·排序算法
秦jh_3 小时前
【C++】哈希扩展
开发语言·c++·哈希算法
苏天夏3 小时前
Passport 插件:Typecho 密码安全的技术守护者
安全·网络安全·php
开发者小天3 小时前
python中使用jupyter notebook 绘制正态分布直方图 密度图 小提琴图 模仿企鹅喙长分布图
开发语言·python·jupyter