首页 > 解决方案 > 在 PHP 中将方括号包含到单个 json 元素中

问题描述

我正在创建一个将 JSON 导出为指定格式的函数。我需要在单个元素中包含方括号。正如您所看到的,“details_order”包含一个带有大括号的元素,我只需要在其中添加一个额外的方括号。请指教,谢谢

原始输出:

[
    {
        "reference": "20190531",
        "orders": [
            {
                "id": "12345",
                "label": "22776",
                "address": "ABC, Apple road",
                "details_orders": {
                    "ref": "AB07-332C"
                }
            }
        ]
    }
]

预期输出:

[
    {
        "reference": "20190531",
        "orders": [
            {
                "id": "12345",
                "label": "22776",
                "address": "ABC, Apple road",
                "details_orders": [
                    {
                        "ref": "AB07-332C"
                    }
                ]
            }
        ]
    }
]

标签: phpjson

解决方案


当您将数据结构编码为 JSON 格式时,只需确保“ref”值存储在“details_orders”数组内的数组中。

下面是如何在 PHP 中构建数据以输出所需 JSON 的示例:

 Array
(
    [0] => Array
        (
            [reference] => 20190531
            [orders] => Array
                (
                    [0] => Array
                        (
                            [id] => 12345
                            [label] => 22776
                            [address] => ABC, Apple road
                            [details_orders] => Array
                                (
                                    [0] => Array
                                        (
                                            [ref] => AB07-332C
                                        )

                                )

                        )

                )

        )

)

下面是如何在 PHP 中初始化这样一个数组:

$data = [
    [
        "reference" => "20190531",
        "orders" => [
            [
                "id" => "12345",
                "label" => "22776",
                "address" => "ABC, Apple road",
                "details_orders" => [
                    [
                        "ref" => "AB07-332C"
                    ]
                ]
            ]
        ]
    ]
];

推荐阅读