将方括号包含到PHP中的单个json元素中

时间:2019-06-02 04:02:07

标签: php json

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

原始代码:

[     {         “参考”:“ 20190531”,         “订单”: [             {                 “ id”:“ 12345”,                 “ label”:“ 22776”,                 “ address”:“ ABC,苹果之路”,                 “ details_orders”:{                     “ ref”:“ AB07-332C”                 }             }         ]     } ]

预期代码:

[     {         “参考”:“ 20190531”,         “订单”: [             {                 “ id”:“ 12345”,                 “ label”:“ 22776”,                 “ address”:“ ABC,苹果之路”,                 “ details_orders”:[                     {                         “ ref”:“ AB07-332C”                     }                 ]             }         ]     } ]

1 个答案:

答案 0 :(得分:0)

将数据结构编码为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"
                    ]
                ]
            ]
        ]
    ]
];