我的数据库中有一个表,其中包含许多家谱树。
-----------------------------
- id name parent_id
-----------------------------
- 1 grandfather NULL
- 2 father 1
- 3 uncle 1
- 4 son 2
- 5 brother 2
- 6 cousin's dauther 7
- 7 cousin 8
- 8 auntie 1
问题是由于边缘情况我无法显示所有名称:
-当我有一个人的 parent_id 比他 parent 的 parent_id 大时 (见表妹的女儿)
我使用这个查询来获取表:
$sql = "SELECT p1.id, p1.name, p1.parent_id FROM pariente p1
ORDER BY p1.parent_id";
$result = $conn->query($sql);
问题是,如果我使用“ORDER BY parent_id”,“cousin's dauther”将不会显示,如果我使用“ORDER BY id”,“cousin”将不会显示。
我使用这个函数将树制作成数组并绘制它:
function make_tree($data, $root) {
$tree = [];
foreach ($data as $node) {
insert($tree, $node);
}
return $tree;
}
function insert(&$root, &$node) {
if (!$root) {
$root = $node;
}
else if ($root["id"] === $node["parent_id"]) {
$root["children"][] = $node;
}
else if (array_key_exists("children", $root)) {
foreach ($root["children"] as &$c) {
if (insert($c, $node)) {
break;
}
}
}
}
function preorder2(&$root) {
if ($root) {
echo "<li>";
echo $root["name"];
if (array_key_exists("children", $root)) {
echo "<ul>";
foreach ($root["children"] as $c) {
preorder2($c);
}
echo "</ul>";
}
echo "</li>";
}
}
?>
在我使用它调用函数之后:
<div>
<?php
while( $row = mysqli_fetch_assoc( $result)){
$resguard[] = $row;
}
$tree = make_tree($resguard);
preorder2($tree);
?>
</div>
最佳答案
我曾经遇到过类似的问题,下面是我的解决方法。
遍历数据集,将每个节点放入您的数组中,并跟踪您想成为根节点的内容。
遍历数组。对于每个parent_id不为null的节点,通过id查找父节点,将当前节点添加为子节点。构建树时无需使用递归。
关于php - 无法在 php 的遍历预序中显示所有树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51938048/