RecursiveParentChildIterator —— 就像 RecursiveDirectoryIterator
有大量使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然不是 SPL,但您可以使用引用 (
&
) 与原生 PHP 构建树:Though not SPL, but you can use references (
&
) build up a tree with native PHP: