JSON对象到数组的转换

时间:2018-12-10 11:07:42

标签: php typo3-extensions

我有一个分配给单个变量'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 个答案:

答案 0 :(得分:1)

您想要的输出可能是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"
                    }
                ]
            ]
        }
    ]
}