NYCPHP Meetup

NYPHP.org

[nycphp-talk] Flattening a Tree

Dan Cech dcech at phpwerx.net
Tue Feb 24 18:12:16 EST 2009


John Campbell wrote:
> 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.

That's pretty slick!

> 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;
> }

It took me a minute to figure out what you're doing there, very neat
approach to handling the sub-arrays!

If you want to retain the keys, you could do something like:

function flatten($input,$separator = '_')
{
  if (!is_array($input)) {
    return false;
  }

  _flatten($input,$output = array(),$separator);

  return $output;
}

function _flatten(&$input,&$output,$sep,$prefix = '')
{
  foreach ($input as $k => $v) {
    $new_k = $prefix ? $prefix . $sep . $k : $k;
    if (is_array($v)) {
      _flatten($v,$output,$sep,$new_k);
    } else {
      $output[$new_k] = $v;
    }
  }
}

Dan




More information about the talk mailing list