无法在php中以遍历顺序显示所有树 [英] Can't get to show all of a tree in a traversal preorder in php
问题描述
我的数据库中有一个表,其中包含许多家谱树.
I have a table in my database that host many genealogy trees.
-----------------------------
- 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
问题是由于出现边缘情况,我无法显示所有名称:
The problem is I can't get to show all the names because of an edge case:
-当我的某人的parent_id大于其父母的parent_id时 (请参阅表弟的女儿)
-When I have a person with a parent_id that is bigger than it's parent's parent_id (see cousin's daugter)
我使用以下查询获取表格:
I use this queries to get the table:
$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",表兄弟的dauther"将不会显示,如果我使用"ORDER BY id","cousin"将不会显示.
The problem is that if I use "ORDER BY parent_id" "cousin's dauther" won't show and if I use "ORDER BY id" "cousin" won't show.
我使用此功能将一棵树制成一个数组并绘制它:
I use this functions to make a the tree into an array and draw it:
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>";
}
}
?>
然后我使用它来调用函数:
And after I use this to call the functions:
<div>
<?php
while( $row = mysqli_fetch_assoc( $result)){
$resguard[] = $row;
}
$tree = make_tree($resguard);
preorder2($tree);
?>
</div>
推荐答案
我曾经遇到过类似的问题,下面是解决问题的方法.
I had a similar problem once, and here's how I fixed it.
-
遍历数据集,将每个节点放入数组中,并跟踪要成为根节点的内容.
Iterate over the dataset, putting each node in your array, and keep track of what you want to be your root node.
遍历数组.对于parent_id不为null的每个节点,请按id查找父节点,然后将当前节点添加为子节点.构建树时无需使用递归.
Iterate over the array. For each node where the parent_id is not null, lookup the parent node by id, and add the current node as a child. There's no need to use recursion when building the tree.
这篇关于无法在php中以遍历顺序显示所有树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!