RecursiveIterator: used to explode tree structure, or only flatten?

Posted by Stephen J. Fuhry on Stack Overflow See other posts from Stack Overflow or by Stephen J. Fuhry
Published on 2010-04-29T14:48:16Z Indexed on 2010/04/29 18:47 UTC
Read the original article Hit count: 305

Filed under:
|
|
|
|

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;
    echo implode(PHP_EOL, $group->getChildren()) . PHP_EOL . PHP_EOL;
}

:END EDIT

© Stack Overflow or respective owner

Related posts about php

Related posts about spl