【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 对象。

相关推荐
lswzw33 分钟前
K8s容器网络排查实战:从宿主机穿透命名空间定位端口监听问题
开发语言·docker·容器
zh73142 小时前
typephp的编译核心phpx原理解析
android·java·开发语言
warpdrivelabs4 小时前
Codex 开源 harness 全面了解
开发语言·人工智能
丰锋ff8 小时前
基于 Qt 的智能门禁系统(二)
开发语言·qt
fpcc8 小时前
跟我学C++中级篇——编译期的条件选择
开发语言·c++
SomeB1oody8 小时前
【RustyML入门】6.3. 并行归约
开发语言·后端·机器学习·rust·教程
mqiqe10 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim10 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
脉动数据行情10 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股
爱学习的小邓同学10 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang