1

即使输入数组不为 null,这也会返回 null:

function flattenArray($multi_array)
{ 
  $flat_array = array();
  foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($multi_array)) as $k => $v) 
  { 
    $flat_array[$k] = $v;
  }

  return $flat_array;
}

任何想法为什么?

4

1 回答 1

0

This works for me on PHP 5.4:

function flattenArray($multi_array)
{
  return iterator_to_array(new RecursiveIteratorIterator(
      new RecursiveArrayIterator($multi_array)), false
  );
}

var_dump(flattenArray([1, 2, 3, [4, 5, [6, 7], 8], 9]));

Partial output:

array(9) {
  [0] =>
  int(1)
  [1] =>
  int(2)
  [2] =>
  int(3)
  [3] =>
  int(4)

The only problem with your code snippet from what I can tell is that the keys are overwritten.

于 2012-07-29T04:03:08.890 回答