【问题标题】:JSON objects to array conversionJSON对象到数组的转换
【发布时间】:2018-12-10 11:07:41
【问题描述】:

我有一个分配给单个变量“数据”的多维数组。我准备的数组如下:

$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"
            ]
        ]
    ]
 } 

有人有解决办法吗? ..提前谢谢

【问题讨论】:

  • json_encode 不产生您的示例输出 - json 中没有 =>,只有 :。你的第二个例子也是一团糟。你确定输出格式吗?我不知道任何混合=>: 并使用一次[] 和另一次{} 的格式。
  • “但我需要以下输出:” - 这甚至不是有效的 JSON。除了=> 问题之外,您不能在 JavaScript 数组中拥有这样的关联键,如果您想要这些键,那么您必须在这些地方使用对象。
  • 请原谅我用“=>”代替“:”。我已经替换了代码。

标签: php typo3-extensions


【解决方案1】:

您想要的输出可能是 java-script 对象/数组,但这不是有效的JSONoutput。您可以在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"
                    }
                ]
            ]
        }
    ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 2013-07-16
    • 2018-04-16
    • 1970-01-01
    • 2016-08-26
    • 2013-08-02
    相关资源
    最近更新 更多