RecursiveParentChildIterator - 类似于RecursiveDirectoryIterator

时间:2010-04-29 14:48:16

标签: php recursion tree spl adjacency-list

有很多使用RecursiveIterator来展平树结构的例子..但是如何用它来爆炸树结构呢?

有一种优雅的方法可以使用它或其他一些SPL库递归构建一个树(读取:将一个平面数组转换成任意深度的数组)给定一个这样的表:

SELECT id, parent_id, name FROM my_tree

修改 您知道如何使用目录执行此操作吗?

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

..如果你能做这样的事情怎么办?

$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

1 个答案:

答案 0 :(得分:2)

虽然不是SPL,但你可以使用引用(&)用本机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);