编程语言
首页 > 编程语言> > php输出json,需要嵌套数组和对象问题

php输出json,需要嵌套数组和对象问题

作者:互联网

https://segmentfault.com/q/1010000009985295

 

        $tmp = [];
            $tmp['id'] = 'aaa';
            $tmp['name'] = 'bbb';
            $tmp['vvvv'] = [
                'www'=>1,
                'ffff'=>2
            ];
            
            echo (json_encode($tmp));

输出是

{
"id": "aaa",
"name": "bbb",
"vvvv": {
    "www": 1,
    "ffff": 2
}
}

我想问一下如何将输出改为

{
"id": "aaa",
"name": "bbb",
"vvvv": [
    {"www": 1},
    {"ffff": 2}
]
}

我测试过这样是可以的,就是不太好用:

 
    $tmp['vvvv'] = [
                0=>(object)['www'=>1],
                1=>(object)['fff'=>2]
            ];




将$tmp['vvvv']里的元素换成数组就行了,不需要转化为object,如下

 
            $tmp = [];
            $tmp['id'] = 'aaa';
            $tmp['name'] = 'bbb';
            $tmp['vvvv'] = [
                ['www'=>1],
                ['ffff'=>2]
            ];

标签:tmp,www,ffff,vvvv,bbb,嵌套,json,php,id
来源: https://www.cnblogs.com/cainiaoaixuexi/p/11405173.html