NYCPHP Meetup

NYPHP.org

[nycphp-talk] Flattening a Tree

John Campbell jcampbell1 at gmail.com
Tue Feb 24 16:24:30 EST 2009


In php 5.3 we should be able to:

function flatten($arr) {
  $result = array();
  array_walk_recursive($arr,function($k,$v) use (&$result) {$result[] = $v});
  return $result;
}

Shows the power of closures & lambdas.

Of course that code is of no use to you.

Try:

function flatten($arr) {
  $result = array_values($arr);
  $i = 0;
  while($i < count($result) )
    is_array($result[$i]) ?
      array_splice($result,$i,1,array_values($result[$i])) :
      $i++;
  return $result;
}

-John Campbell



More information about the talk mailing list