RecursiveParentChildIterator —— 就像 RecursiveDirectoryIterator

发布于 2024-08-30 09:08:57 字数 762 浏览 3 评论 0原文

有大量使用 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲鸠 2024-09-06 09:08:57

虽然不是 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);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文