php 多维数组上的 json_encode() - 带有字符串键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16419689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:05:18  来源:igfitidea点击:

json_encode() on a multidimensional array - with string keys

phpmultidimensional-arrayjson

提问by Patrick

I am creating an very large multidimensional array using PHP. Each object contains Name, ID, ParentID and Children. Children is an array of more objects in the same format.

我正在使用 PHP 创建一个非常大的多维数组。每个对象包含名称、ID、ParentID 和 Children。Children 是具有相同格式的更多对象的数组。

It is critical I name the IDs of each object - this helps me put each object under the correct parent. (In the code below, I use 101, 102 etc.)

我命名每个对象的 ID 很重要 - 这有助于我将每个对象放在正确的父项下。(在下面的代码中,我使用 101、102 等)

However, the problem I am having is when I return the array in JSON using json_encode. Each 'Children' array is being printed as an object, not an array - as shown in the JSON code below.

但是,我遇到的问题是当我使用json_encode. 每个“Children”数组都被打印为一个对象,而不是一个数组——如下面的 JSON 代码所示。

As I read on another SO thread here, they "are made as objects because of the inclusion of string keys" - although they are numbers, they are still strings.

正如我在此处的另一个 SO 线程上阅读的那样,它们“由于包含字符串键而被制作为对象”-尽管它们是数字,但它们仍然是字符串。

{
"101": {
    "ID": "101",
    "ParentID": "0",
    "Name": "Root One"
    "Children": {
        "102": {
            "ID": "102",
            "ParentID": "101",
            "Name": "Child One"
        },
        "103": {
            "ID": "103",
            "ParentID": "101",
            "Name": "Child Two",
            "Children": {
                "104": {
                    "ID": "104",
                    "ParentID": "103",
                    "Name": "Child Child One"
                }
            }
        },

Does anyone know how to overcome this issue?

有谁知道如何克服这个问题?

Edit:The JSON should look like this (the square brackets are important!):

编辑:JSON 应该是这样的(方括号很重要!):

[
{
    "ID": "101",
    "ParentID": "0",
    "Name": "Root One",
    "Children": [
        {
            "ID": "102",
            "ParentID": "101",
            "Name": "Child One",
            "Children": [

采纳答案by Patrick

I have now got a working solution which is fast and works well.

我现在有了一个快速且运行良好的工作解决方案。

  1. Firstly, as written in SO link from the question;

    In JSON, arrays only have numeric keys, whereas objects have string properties. The inclusion of a array key forces the entire outer structure to be an object by necessity.

    In JSON; Curly braces hold objects ({}), Square brackets hold arrays ([]).

  2. So using a string as a key will result in the json_encodefunction returning objects, whereas reseting the keys will ensure it creates arrays.

  3. Therefore, just before I return my JSON encoded string, I run a function to reset all the array keys. The code I found on this SO thread (Reset array keys in multidimensional array)was particularly useful!

  1. 首先,正如问题中的 SO 链接所写的那样;

    在 JSON 中,数组只有数字键,而对象具有字符串属性。包含数组键迫使整个外部结构必须成为一个对象。

    在 JSON 中;花括号保存对象 ( {}),方括号保存数组 ( [])。

  2. 因此,使用字符串作为键将导致json_encode函数返回对象,而重置键将确保它创建数组。

  3. 因此,就在我返回 JSON 编码的字符串之前,我运行了一个函数来重置所有数组键。我在这个 SO 线程上找到的代码(在多维数组中重置数组键)特别有用!

回答by deceze

A JSON array has no explicit indexes, it's just an ordered list. The only JSON data structure that has named keysis an object. The literal should make this quite obvious:

JSON 数组没有明确的索引,它只是一个有序列表。唯一具有命名键的JSON 数据结构是对象。文字应该使这一点非常明显:

["foo", "bar", "baz"]

This arrayhas no named indices and there isn't any provision to add any.

这个数组没有命名索引,也没有任何添加的规定。

PHP conflates both lists and key-value stores into one arraydata type. JSON doesn't.

PHP 将列表和键值存储合并为一种array数据类型。JSON 没有。

回答by Eugen Mihailescu

This is your object:

这是你的对象:

$parent=new StdClass();
$parent->ID=101;
$parent->ParentID=0;
$parent->Name='Root One';

$child1=new StdClass();
$child1->ID=1011;
$child1->ParentID=$parent->ID;
$child1->Name='Child One';
$parent->Children[]=$child1;


$child1_1=new StdClass();
$child1_1->ID=10111;
$child1_1->ParentID=$child1->ID;
$child1_1->Name='Child One One';
$child1->Children[]=$child1_1;    

This is your JSON convert function:

这是您的 JSON 转换函数:

echo json_encode($parent,JSON_PRETTY_PRINT);

and this is your object coded into JSON format:

这是您编码为 JSON 格式的对象:

{
    "ID": 101,
    "ParentID": 0,
    "Name": "Root One",
    "Children": [
        {
            "ID": 1011,
            "ParentID": 101,
            "Name": "Child One",
            "Children": [
                {
                    "ID": 10111,
                    "ParentID": 1011,
                    "Name": "Child One One"
                }
            ]
        }
    ]
}

The answer came later because I started learning PHP later. Anyway, some day, someone might find it useful.

后来得到了答案,因为我是后来开始学习 PHP 的。无论如何,总有一天,有人可能会发现它很有用。

回答by Damien Overeem

http://php.net/manual/en/function.json-decode.php

http://php.net/manual/en/function.json-decode.php

Set 2nd parameter of json_decode to true to atleast get assoc arrays.

将 json_decode 的第二个参数设置为 true 以至少获取关联数组。

Aside from that: javascript can't handle non-sequential/non-contiguous array indexes, so as soon as the id's are not sequential, json has no other option then to convert it into "string" indexes.

除此之外:javascript 无法处理非连续/非连续数组索引,因此只要 id 不是连续的,json 就没有其他选择,然后将其转换为“字符串”索引。