递归ParentChilditerator - 像递归授权介质器一样
-
02-10-2019 - |
题
有许多使用递归材料来扁平树结构的示例。但是,使用它来爆炸树结构呢?
是否有一种优雅的方法来使用此方法,或者其他一些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();
}
:结束编辑
解决方案
虽然不是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);
不隶属于 StackOverflow