在PHP中保留键值对时展平数组

时间:2017-01-26 02:38:28

标签: php arrays recursion multidimensional-array flatten

我有一个这样的数组:

array (size=4)
  0 =>
    array (size=4)
      key => value
      key => value
      key => value
      key => value
  1 =>
    array (size=2)
      key => value
      key => value
  2 =>
    array (size=1)
      key => value
  3 =>
    array (size=1)
      key => value

我想将数组展平为:

array (size=4)
  key => value
  key => value
  key => value
  key => value
  key => value
  key => value
  key => value
  key => value

我使用array_mergearray_walk_recursiveRecursiveIteratorIterator以及RecursiveArrayIterator等内容尝试了我自己的解决方案。我还尝试了在StackOverflow上发布类似问题的许多解决方案,但它们都没有按照我的预期运行。它们要么不保留键值对,要么给我一个与原始数组相同的数组。我的尝试看起来像这样:

$multidimensionalArray = array(stuff goes here);
$flatArray = array();

function flattenArray ($array) {
  foreach ($array as $key => $value) {
    if (is_array($value) {
      flattenArray($value);
    }
    else {
      $flatArray[$key] = $value;
    }
  }
}

flattenArray($multidimensionalArray);

1 个答案:

答案 0 :(得分:0)

我想知道RecursiveArrayIterator会出现什么问题,因为你只需要使用最简单的foreach循环从迭代器中收集键/值对:

$a = [
  0 => ['a' => 1, 'b' => 2],
  1 => ['x' => 3, 'y' => 4],
  2 => 5,
  3 => ['m' => 6, ['k' => 7, 'n' => 8]],
];

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));

foreach ($it as $key => $value) {
  $result[$key] = $value;
}

print_r($result);

输出:

Array
(
    [a] => 1
    [b] => 2
    [x] => 3
    [y] => 4
    [2] => 5
    [m] => 6
    [k] => 7
    [n] => 8
)