json_encode PHP 数组作为 JSON 数组而不是 JSON 对象 [英] json_encode PHP array as JSON array not JSON object

查看:30
本文介绍了json_encode PHP 数组作为 JSON 数组而不是 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 中有以下数组:

数组([0] =>大批([id] =>0[名称] =>姓名1[short_name] =>n1)[2] =>大批([id] =>2[名称] =>姓名2[short_name] =>n2))

我想将其 JSON 编码为 JSON 数组,生成如下所示的字符串:

<预><代码>[{id":0,名称":名称1",short_name":n1"},{id":2,名称":名称 2",short_name":n2"}]

但是当我在这个数组上调用 json_encode 时,我得到了以下:

<代码>{0":{id":0,名称":名称1",short_name":n1"},2":{id":2,名称":名称 2",short_name":n2"}}

哪个是对象而不是数组.

如何让 json_encode 将我的数组编码为数组?

解决方案

参见 RFC 8259 中的数组JavaScript 对象表示法 (JSON) 数据交换格式:

<块引用>

数组结构表示为围绕零的方括号或更多值(或元素).元素以逗号分隔.

array = begin-array [ value *( value-separator value ) ] end-array

您正在观察这种行为,因为您的数组不是连续的 - 它有键 02,但没有 1 作为一把钥匙.

仅有数字索引是不够的.json_encode 只会在您的 PHP 数组是连续的情况下将您的 PHP 数组编码为 JSON 数组 - 也就是说,如果它的键是 0、1、2、3、...

您可以使用 array_values 函数按顺序重新索引您的数组以获得你想要的行为.例如,以下代码在您的用例中成功运行:

echo json_encode(array_values($input)).

I have the following array in PHP:

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => name1
            [short_name] => n1
        )

    [2] => Array
        (
            [id] => 2
            [name] => name2
            [short_name] => n2
        )
)

I want to JSON encode it as a JSON array, producing a string like the following:

[  
    {  
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    {  
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
]

But when I call json_encode on this array, I get the following:

{  
    "0":{  
        "id":0,
        "name":"name1",
        "short_name":"n1"
    },
    "2":{  
        "id":2,
        "name":"name2",
        "short_name":"n2"
    }
}

Which is an object instead of an array.

How can I get json_encode to encode my array as an array, instead?

解决方案

See Arrays in RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format:

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

You are observing this behaviour because your array is not sequential - it has keys 0 and 2, but doesn't have 1 as a key.

Just having numeric indexes isn't enough. json_encode will only encode your PHP array as a JSON array if your PHP array is sequential - that is, if its keys are 0, 1, 2, 3, ...

You can reindex your array sequentially using the array_values function to get the behaviour you want. For example, the code below works successfully in your use case:

echo json_encode(array_values($input)).

这篇关于json_encode PHP 数组作为 JSON 数组而不是 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆