-2

我对 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 ",
      }
    ]
  }
}

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

请你帮助我好吗?问候

4

1 回答 1

1

要实现这种格式,您必须稍微修改 $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"
            }
        }
    ]
}
于 2021-01-29T20:14:33.347 回答