NYCPHP Meetup

NYPHP.org

[nycphp-talk] Flattening a Tree

csnyder chsnyder at gmail.com
Wed Feb 25 00:13:02 EST 2009


On Tue, Feb 24, 2009 at 3:52 PM, charlie derr <cderr at simons-rock.edu> wrote:
> Ajai Khattri wrote:
>>
>> On Tue, 24 Feb 2009, csnyder wrote:
>>
>>> What are you fishing for? Write some code and try it.
>>
>>
>> Nice.
>
>
> I initially had a similar reaction when I saw this comment, but when I
> really thought about it, that's the power of PHP (that it's  so easy to just
> try stuff).

Well, no, he's right. I was just being mean because I underestimated
how mind-bending the problem is.

You have to pass your new array by reference, but you also have to
pass the current key you're working on so that it can be prepended to
new keys as you traverse them.

My code is similar to Dan's:

<?php

function flatten( $array, &$flatarray, $currentkey ) {
  foreach( $array AS $key=>$val ) {
    $nextkey = $currentkey.'_'.$key;
    if ( is_array( $val ) ) {
      flatten( $val, $flatarray, $nextkey );
    }
    else {
      $flatarray[ $nextkey ] = $val;
    }
  }
}

$array = array( 'a'=>array('b'=>'bee', 'c'=>'cee' ), 'b'=>array(
'd'=>'dee', 'e'=>'eee', 'f'=>array('g'=>'gee', 'h'=>'hee' ) ) );
$flat = array();

foreach ( $array AS $key=>$val ) {
  if ( is_array( $val )) {
    flatten( $val, $flat, $key );
  }
  else {
    $flat[ $key ] = $val;
  }
}

That took all of ten minutes to write and test, but there was
definitely an "oh shi... " moment figuring out how to get the keys
right.



More information about the talk mailing list