views:

114

answers:

1

There are tons of examples of using the RecursiveIterator to flatten a tree structure.. but what about using it to explode a tree structure?

Is there an elegant way to use this, or some other SPL library to recursively build a tree (read: turn a flat array into array of arbitrary depth) given a table like this:

SELECT id, parent_id, name FROM my_tree

EDIT: You know how you can do this with Directories?

$it = new RecursiveDirectoryIterator("/var/www/images");
foreach(new RecursiveIteratorIterator($it) as $file) {
    echo $file . PHP_EOL;
}

.. What if you could do something like this:

$it = new RecursiveParentChildIterator($result_array);
foreach(new RecursiveIteratorIterator($it) as $group) {
    echo $group->name . PHP_EOL;
    // this would contain all of the children of this group, recursively
    $children = $group->getChildren();
}

:END EDIT

+2  A: 

Though not SPL, but you can use references (&) build up a tree with native PHP:

// untested
$nodeList = array();
$tree     = array();
foreach ($result as $row) {
    $nodeList[$row['id']] = array_merge($row, array('children' => array()));
}
foreach ($nodeList as $nodeId => &$node) {
    if (!$node['parent_id'] || !array_key_exists($node['parent_id'], $nodeList)) {
        $tree[] = &$node;
    } else {
        $nodeList[$node['parent_id']]['children'][] = &$node;
    }
}
unset($node);
unset($nodeList);
Stefan Gehrig
This seems to be the best solution that I have come across so far (they use the same process here: http://bit.ly/4IyIBR ). I appreciate its sneaky way of avoiding recursion -- a process I find is best reserved for some sort of a reusable pattern, such as those provided in the SPL library.
Stephen J. Fuhry