search

Home  >  Q&A  >  body text

PHP outputs json, which requires nested arrays and objects.

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

The output is

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

I would like to ask how to change the output to

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

I have tested that this works, but it is not very easy to use:

    $tmp['vvvv'] = [
                0=>(object)['www'=>1],
                1=>(object)['fff'=>2]
            ];
为情所困为情所困2769 days ago735

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-30 09:57:13

    Just replace the elements in $tmp['vvvv'] with an array. There is no need to convert them into objects, as follows

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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-06-30 09:57:13

    That’s how it is, all PHP is map

    reply
    0
  • Cancelreply