转换为XML时将重复的键保留在数组中-PHP

时间:2018-10-08 10:29:08

标签: php arrays xml

我正在使用使用XML作为输入格式的API。我从头开始创建JSON到XML,但是我发现数组由于相同的键而被截断了?

这是我的JSON的样子:

$order_data = array([
    "media_id" => 'FACE',
    "headline" => 'FACEBOOK FEBRUAR 2018',
    "agreement_id" => '****',
    "client_contact" => "Asim",
    "insertion" => [       
        "insertion_date" => '2018-10-08',
        "start_date" => '2018-10-08',
        "end_date" => "2018-10-09",
        "PO_number" => 150,
        "price_row" => [
            "price_code" => '000',
            "gross" => 11111
        ],
    ],
    "insertion" => [       
        "insertion_date" => '2018-09-25',
        "start_date" => '2018-09-25',
        "end_date" => "2018-10-10",
        "PO_number" => 150,
        "price_row" => [
            "price_code" => '000',
            "gross" => 10002345
        ],

    ],
]);

这是我print_r($order_data)的时间:

array(1) {
  [0]=>
  array(7) {
    ["media_id"]=>
    string(4) "FACE"
    ["headline"]=>
    string(21) "FACEBOOK FEBRUAR 2018"
    ["agreement_id"]=>
    string(4) "****"
    ["client_contact"]=>
    string(10) "Asim"
    ["insertion"]=>
    array(5) {
      ["insertion_date"]=>
      string(10) "2018-09-25"
      ["start_date"]=>
      string(10) "2018-09-25"
      ["end_date"]=>
      string(10) "2018-10-10"
      ["PO_number"]=>
      int(150)
      ["price_row"]=>
      array(2) {
        ["price_code"]=>
        string(3) "000"
        ["gross"]=>
        int(10002345)
      }
    }
  }
}

重复数组insertion已删除,我知道这不是具有重复键的可选方法,但这是API的要求。有人知道我如何保留重复项吗?



我也尝试过以下格式:

"insertion" => [       
    "insertion_date" => '2018-10-08',
    "start_date" => '2018-10-08',
    "end_date" => "2018-10-09",
    "PO_number" => 150,
    "price_row" => [
        "price_code" => '000',
        "gross" => 11111
    ],
    "insertion_date" => '2018-09-25',
    "start_date" => '2018-09-25',
    "end_date" => "2018-10-10",
    "PO_number" => 150,
    "price_row" => [
        "price_code" => '000',
        "gross" => 10002345
    ],
],

print_r($order_data)仍然与上述相同

1 个答案:

答案 0 :(得分:0)

根据规则,您不能在同一级别上给数组中的键命名相同的名称。但是您可以像这样向该键添加多个子数组:-

$order_data = array([
    "media_id" => 'FACE',
    "headline" => 'FACEBOOK FEBRUAR 2018',
    "agreement_id" => '****',
    "client_contact" => "Asim",
    "insertion" => [
        [
            "insertion_date" => '2018-10-08',
            "start_date" => '2018-10-08',
            "end_date" => "2018-10-09",
            "PO_number" => 150,
            "price_row" => [
                "price_code" => '000',
                "gross" => 11111
            ]
        ],
        [
            "insertion_date" => '2018-09-25',
            "start_date" => '2018-09-25',
            "end_date" => "2018-10-10",
            "PO_number" => 150,
            "price_row" => [
                "price_code" => '000',
                "gross" => 10002345
            ]
        ]
    ]
]);

尝试一下。我认为这会对您有所帮助。