简体   繁体   中英

Using RecursiveIterator to flatten my multi array not working?

This returns null even if the input array is not 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;
}

Any ideas why?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM