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

相关推荐
似水明俊德6 分钟前
07-C#
开发语言·c#
浩子智控26 分钟前
python程序打包的文件地址处理
开发语言·python·pyqt
Jackey_Song_Odd30 分钟前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python
Elnaij40 分钟前
从C++开始的编程生活(20)——AVL树
开发语言·c++
似水明俊德43 分钟前
12-C#
开发语言·数据库·oracle·c#
hanbr44 分钟前
【C++ STL核心】vector:最常用的动态数组容器(第九天核心)
开发语言·c++
菜鸟‍2 小时前
【后端项目】苍穹外卖day01-开发环境搭建
java·开发语言·spring boot
青槿吖2 小时前
【保姆级教程】Spring事务控制通关指南:XML+注解双版本,避坑指南全奉上
xml·java·开发语言·数据库·sql·spring·mybatis
Yungoal2 小时前
B/S和C/S架构在服务端接收请求
c语言·开发语言·架构
niceffking2 小时前
C++内部类的ISO约定和语法细节
开发语言·c++