Re: Function to Build Trees

From: Date: Sun, 19 Aug 2001 21:36:17 +0000
Subject: Re: Function to Build Trees
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-63424@lists.php.net to get a copy of this message
> Given a multidimensional array with words as keys, I want to match > the values of each array with the keys of the array and build a new > array that reflects these relationships as a sort of tree. So, in > the list below, "fruit", "apples", "oranges", "red" are > the keys and > in the "fruit" array are the values "apples" and "oranges", so I > want > the function to create a new array that looks like: > > ORIGINAL ARRAY: > $array['fruits'] = array("apples","oranges","pears"); > $array['apples'] = array("red","granny smith"); > $array['oranges'] = array('mandarin'); > $array['red'] = array("big red","small red"); > > NEW ARRAY: > $array['fruits'] = array(apples,oranges,pears); > $array['fruits']['apples'] = array("red","granny > smith"); > $array['fruits']['oranges'] = array('mandarin'); Something not unlike this: # UNTESTED CODE: # Change the 1's to 0's to get rid of debugging output: function buildTree(&$original, $key = 'fruits', $level = 1){ if (1) echo str_repeat('&gt;', $level), $key, "&nbsp;&nbsp;&nbsp;-&gt;", key($original), "<BR>\n"; $result = array(); if (is_array($original[$key])){ while (list($k, $v) = each($original[$key])){ $result[$key][$k] = buildTree($v, $k, $level++); } } else{ $result[$key][$k] = $value; } if (1) echo str_repeat('&lt;', $level), "<BR>\n"; return $result; } -- WARNING richard@zend.com address is an endangered species -- Use ceo@l-i-e.com Wanna help me out? Like Music? Buy a CD: http://l-i-e.com/artists.htm Volunteer a little time: http://chatmusic.com/volunteer.htm

« previous php.general (#63424) next »