Function to Build Trees
| From: | Sondra Russell | Date: | Sun, 19 Aug 2001 17:14:58 +0000 |
| Subject: | Function to Build Trees | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-63409@lists.php.net to get a copy of this message | ||
Hello everyone,
I've been tearing my hair out trying to write a function in PHP that will accomplish the following:
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');
And then I want it further to figure out that "red", now in the array found at: $array['fruits']['apples'] matches a key in the original array so the final result looks like:
FINAL ARRAY:
$array['fruits'] = array(apples,oranges,pears);
$array['fruits']['oranges'] = array('mandarin');
$array['fruits']['apples'] = array("red","granny smith");
$array['fruits']['apples']['red'] = array("big red","small red");
So, you see how it builds a little tree, right?
AND, I'd like this function to be able to handle any number (probably less that 30, but whatever) of initial array elements in an unpredictable order and the final tree could have up to five or six levels. You know?
Is this impossible, or am I just going about the end result wrong?? It seemed like such a simple thing three days ago, but now I am about to cry uncle.
Anyway, please write if you have any thoughts.
Best,
Sondra Russell