解析json_decoded php数组的最佳方法

时间:2018-11-13 21:14:20

标签: php parsing

解析字符串化一维数组的最佳方法是什么?

输入数组

$inputArray = array(
  "id" => "foo",
  "name" => "bar",
  "money[0][amount]" => 30,
  "money[0][countryCode]" => "US",
  "money[1][amount]" => 25,
  "money[1][countryCode]" => "CA",
)

所需的输出数组

$outputArray = array(
  "id" => "foo",
  "name" => "bar",
  "money" => array(
    [0] => array(
      "amount" => 30,
      "countryCode" => "US"
    ),
    [1] => array(
      "amount" => 25,
      "countryCode" => "CA"
    ),
  ),
)

1 个答案:

答案 0 :(得分:3)

您可以将数组转换成查询网址,然后解析它……就像这样

<?php

$inputArray = array(
  "id" => "foo",
  "name" => "bar",
  "money[0][amount]" => 30,
  "money[0][countryCode]" => "US",
  "money[1][amount]" => 25,
  "money[1][countryCode]" => "CA",
);

$url = http_build_query($inputArray);
parse_str($url, $outputArray);

print_r($outputArray);

实时示例:https://3v4l.org/DAAUM