通过递归将多维数组转换为简单数组

时间:2015-03-26 13:33:01

标签: php arrays recursion multidimensional-array

如何转换此数组:

$array = [
    "order" => [
        "items" => [
            "6" => [
                "ndc" => "This value should not be blank."
            ],
            "7" => [
                "ndc" => "This value should not be blank."
            ]
        ]
    ]
];

$array = [
    "order[items][6][ndc]" => "This value should not be blank.",
    "order[items][7][ndc]" => "This value should not be blank.",
];

第一个数组可能具有无限数量的嵌套级别。所以嵌套的foreach不是一种选择。

我花了很多时间寻找解决方案而一无所获。有人可以帮助或指导我吗?

1 个答案:

答案 0 :(得分:4)

这样的事情应该可以胜任:

$newArr = [];

function reduce_multi_arr($array, &$newArr, $keys = '') {
  if (!is_array($array)) {
      $newArr[$keys] = $array;
  } else {
      foreach ($array as $key => $val) {
        if ($keys === '') $nextKey = $key; // first key
        else $nextKey = '[' . $key . ']'; // next [keys]
        reduce_multi_arr($val, $newArr, $keys . $nextKey);
      }
  }
}

reduce_multi_arr($array, $newArr);

print_r($newArr);

输出:

Array
(
    [order[items][6][ndc]] => 'This value should not be blank.'
    [order[items][7][ndc]] => 'This value should not be blank.'
)