JSON对象进行数组转换

我有一个多维数组分配给单个变量'data' . 我准备如下数组:

$img1 = [
    'title' => 'example',
    'description' => 'description'
];
$imagesArray[] = [
     'img1' => [
        'normal' => $img1
     ]
 ];
$data = [
     'data' => [
        'images' => $imagesArray
    ],
    'message' => 'OK'
 ];

将其编码为JSON数组时,会生成以下输出 .

{
    "images":{
        "normal":{
            {
            "title" : "example1",
            "description" : "description1"
            },
            {
            "title" : "example2",
            "description" : "description2"
            }
        }
    }
 }

但我需要以下输出:

{
    "images":[
        "normal":[
            [
            "title" : "example1",
            "description" : "description1"
            ],
            [
            "title" : "example2",
            "description" : "description2"
            ]
        ]
    ]
 }

有人有解决方案吗? ..提前致谢

回答(1)

2 years ago

您想要的输出可能是java脚本对象/数组,但这不是有效的 JSON 输出 . 您可以在https://jsonlint.com中检查所需的输出 .

你的最终数据应该是

$data = [
                'images' => [
                    [
                        'normal' => [
                            [
                                [
                                    'title' => 'example1'
                                ],
                                [
                                    'description' => 'description1'
                                ]
                            ],
                            [
                                [
                                    'title' => 'example2'
                                ],
                                [
                                    'description' => 'description2'
                                ]
                            ]
                        ]
                    ]
                ]
            ];

这会将数组转换为JSON之类的

{
    "images": [
        {
            "normal": [
                [
                    {
                        "title": "example1"
                    },
                    {
                        "description": "description1"
                    }
                ],
                [
                    {
                        "title": "example2"
                    },
                    {
                        "description": "description2"
                    }
                ]
            ]
        }
    ]
}