json_decode() 使用总结

本文深入探讨了PHP中JSON编码与解码的细节,包括如何使用json_encode和json_decode处理数组与对象,以及如何通过参数控制输出格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

json使用总结

1、php json_encode() 返回 [] 与 {}

  1. json_decode() 原样输出:
    encode之前是数组,decode为数组;
    encode之前是对象,decode为对象;
  2. json_decode(a, true) 数组格式输出
<?php
       $a = [
            ['a','b','c'],
            [],
            [1,2,3]
        ];
        $b = json_encode($a);
        // [["a","b","c"],[],[1,2,3]]
        $c = json_encode($a, JSON_FORCE_OBJECT);
        // {"0":{"0":"a","1":"b","2":"c"},"1":{},"2":{"0":1,"1":2,"2":3}}
?>
<?php
print_r(json_decode($b));
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
)
?>
<?php
print_r(json_decode($b, true));
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
)
?>
<?php
print_r(json_decode($c));
stdClass Object
(
    [0] => stdClass Object
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => stdClass Object
        (
        )

    [2] => stdClass Object
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
)
?>
<?php
print_r(json_decode($c,true));
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
)
?>

参考:https://www.codelovers.cn/article/20180629104213.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值