创建多维数组,并处理json_encode的相同键名问题

时间:2020-04-11 10:35:21

标签: php json

我正在尝试遵守具有多个具有相同键名的项的集成要求,包括将其元数据放入主数组中以正确进行json_encode。

我尝试拆分并加入数组array_push。我唯一可行的解​​决方案是手动构建json包的这一部分。任何帮助将不胜感激。

以下是我正在努力的示例:

$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";

$message_pack["ItemDetail"]["ItemName"] = "Item1";
$message_pack["ItemDetail"]["ItemCode"] = "123";
$message_pack["ItemDetail"]["Itemname"] = "Item2";
$message_pack["ItemDetail"]["ItemCode"] = "234"; 

$json_msg = json_encode($message_pack);

这显然只会采用传递给匹配键名的最后一个值。

我需要坚持这种json格式:

{
  "Header": {
    "Sequence": "TEST1",
    "TC": "1", 
  },

  "ItemDetail": [{
        "ItemName": "Item1",
        "ItemCode": "123" }

   {    "ItemName": "Item2",
        "ItemCode": "234" }]
}

1 个答案:

答案 0 :(得分:2)

您需要将“ ItemDetail”设置为数组,否则将覆盖$message_pack["ItemDetail"]["Itemname"]$message_pack["ItemDetail"]["ItemCode"]

<?php

$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"][] = ["ItemName" => "Item1", 'ItemCode' => 123];
$message_pack["ItemDetail"][] = ["ItemName" => "Item2", 'ItemCode' => 234];

$json_msg = json_encode($message_pack, JSON_PRETTY_PRINT);
echo ($json_msg);

将输出:

{
    "Header": {
        "Sequence": "TEST1",
        "TC": "1"
    },
    "ItemDetail": [
        {
            "ItemName": "Item1",
            "ItemCode": 123
        },
        {
            "ItemName": "Item2",
            "ItemCode": 234
        }
    ]
}