简体   繁体   English

如何使用 PHP json_encode 用 [] 格式化数组数据

[英]How to use PHP json_encode to format array data with []

Goal: Use json_encode to format array data into a specified format目标:使用json_encode将数组数据格式化成指定格式

This is the needed format for the data after running through PHP json_encode:这是运行PHP json_encode后数据所需的格式:

NEEDED FORMAT需要的格式

{
    "top_level_data": [
     {
        "extension": {},
        "sub_level_data1": 0
     }
    ]
}

When I use this PHP:当我使用这个 PHP 时:

$data = array('top_level_data' => array('extension' => array(),
                                'sub_level_data1' => 0
                                )
            )
$data = json_encode($data);

I get this incorrect Output:我得到这个不正确的 Output:

{
    "top_level_data":{
        "extension":[],
        "sub_level_data1": 0
        }
}

Question: How can I modify my php to include the {} and the [] in the correct places as the Needed Format?问题:如何修改我的 php 以将 {} 和 [] 作为所需格式包含在正确的位置?

It's not clear how you're generating $data ;目前尚不清楚您是如何生成$data的; if it's by the assignment you show then you can just add an extra layer of array at top_level_data , and cast the extension value to an object:如果是通过您显示的分配,那么您可以在top_level_data添加额外的array层,并将extension值转换为 object:

$data = array('top_level_data' => array(
                                    array('extension' => (object)array(),
                                          'sub_level_data1' => 0
                                          )
                                        )
            );

If however you get the $data from another source, you can modify it like this:但是,如果您从其他来源获取$data ,您可以像这样修改它:

$data['top_level_data']['extension'] = (object)$data['top_level_data']['extension'];
$data['top_level_data'] = array($data['top_level_data']);

Both methods yield this JSON:两种方法都会产生这个 JSON:

{
    "top_level_data": [
        {
            "extension": {},
            "sub_level_data1": 0
        }
    ]
}

Demo on 3v4l.org 3v4l.org 上的演示

json_encode will encode sequence array with [] . json_encode将使用[]对序列数组进行编码。 The sequence array should has index from 0 to n .序列数组的索引应该从0n For other array, associative array and object will encoded with {} .对于其他数组,关联数组和 object 将使用{}进行编码。 Use the JSON_FORCE_OBJECT parameter of json_encode all the array will be encoded with {} .使用json_encodeJSON_FORCE_OBJECT参数,所有数组都将使用{}进行编码。

Example:例子:

echo json_encode(range(1,3));                     // [1,2,3]
echo json_encode(array(2=>2));                    // {"2":2}
echo json_encode(range(1,3),JSON_FORCE_OBJECT);   // {"0":1,"1":2,"2":3}
echo json_encode((object)range(1,3));             // {"0":1,"1":2,"2":3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM