我的数据库中有一个表,其中包含许多家谱树。
-----------------------------
- 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_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”“堂兄的女儿”将不会显示,如果我使用“ORDER BY id”“堂兄”将不会显示。
我使用这个函数将树变成一个数组并绘制它:
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>