有很多使用RecursiveIterator来夷平树结构的例子。但是用它炸掉树结构呢?
是否有一种优雅的方法可以使用此库或其他一些SPL库递归地构建树(read:将平面数组转换为任意深度的数组)?
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();
}:结束编辑
发布于 2010-04-29 17:06:32
虽然不是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);https://stackoverflow.com/questions/2738278
复制相似问题