在 php 中使用 json_encode 的 json 格式的根名称和子名称

Root name and child name for json format using json_encode in php

我在使用 json_encode 时遇到了一些问题, 我需要输出是这样的:

{
  "Advisories": [
    {
      "Advisory": {
        "Severe": "false",
        "description": "Lorem ipsum dolor sit amet",
        "title": "Advise:",
      }
    },
    {
      "Advisory": {
        "Severe": "true",
        "description": "Lorem ipsum dolor sit amet",
        "title": "Advise:",
      }
    },
    {
      "Advisory": {
        "Severe": "true",
        "description": "Lorem ipsum dolor sit amet",
        "title": "Advise:",
      }
    }
  ]
}

我的 var $arrayItems 是这样的:

Array (
    [0] => Array (
        [Severe] => false
        [description] => Lorem ipsum dolor sit amet.
    [title] => Advise
    )
    [1] => Array (
        [Severe] => false
        [description] => Lorem ipsum dolor sit amet.
    [title] => Advise
    )
    [2] => Array (
        [Severe] => true
        [description] => Lorem ipsum dolor sit amet
    [title] => Advise
    )
)

但是当我像这样使用函数 json_encode 时:print json_encode(['Advisories' => array('Advisory'=>$arrayItems)]); 输出是这样的:

{
  "Advisories": {
    "Advisory": [
      {
        "Severe": "false",
        "description": "Lorem ipsum dolor sit amet",
        "title": "Advise",
      },
      {
        "Severe": "false",
        "description": "Lorem ipsum dolor sit amet",
        "title": "Advise",
      },
      {
        "Severe": "true",
        "description": "Lorem ipsum dolor sit amet",
        "title": "Advises ",
      }
    ]
  }
}

我不知道我还能做些什么来改变输出,

你能帮帮我吗? 此致

要实现该格式,您必须稍微修改 $arrayItems。

下面的代码片段将修改每个子数组以包含 'Advisory' 键,该键将是指向 json 对象(保存原始子数组数据)的 属性。

$result = ['Advisories' => array_map(
    function ($subarray) {
        return ['Advisory' => $subarray];
    },
    $arrayItems
)];

return json_encode($result);

结果:

{
    "Advisories": [
        {
            "Advisory": {
                "Severe": false,
                "description": "Lorem ipsum dolor sit amet.",
                "title": "Advise"
            }
        },
        {
            "Advisory": {
                "Severe": false,
                "description": "Lorem ipsum dolor sit amet.",
                "title": "Advise"
            }
        },
        {
            "Advisory": {
                "Severe": true,
                "description": "Lorem ipsum dolor sit amet",
                "title": "Advise"
            }
        }
    ]
}