1

有大量使用 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();
}

:结束编辑

4

1 回答 1

2

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);
于 2010-04-29T17:06:32.667 回答