php - 用 php 显示存储在数据库中的家谱树
问题描述
我的数据库(mysql)中有一个带有下一个模式的表:
-----------------------------
- id name parent_id
-----------------------------
- 1 grandfather NULL
- 2 father 1
- 3 uncle 1
- 4 son 2
- 5 brother 2
- 6 sister 2
我想通过以下方式在我的页面上显示它:
grandfather
father
son
brother
sister
Uncle
(前序遍历)
这是我找到的最佳解决方案(不起作用)
$sql = "SELECT p1.id, p1.name, p1.parent_id FROM tree p1 ORDER BY p1.id";
$result = $conn->query($sql);
while($row = mysqli_fetch_assoc($result)) {
arbol($row, $result);
};
function arbol($fila, $result) {
echo $fila["name"] . "<br>";
$flag = false;
while($busqueda = mysqli_fetch_row($result)) {
if($busqueda[2]==$fila["id"]){
$flag = true;
break;
}
};
if ($flag){
foreach ($result as $ruta) {
if($ruta["parent_id"]==$fila["id"]){
arbol($ruta, $result);
};
};
} else {
return;
}
};
};
因此,我第一次遍历到底部,但从未遍历树的其余部分:
Grandfather
parent
son
我做错了什么?或者你有什么建议?
注意:完成后,我会有很多“祖父”,这就是为什么会有一段时间(我会在那里添加一个“parent_id=NULL”条件)。
编辑:执行此操作后的行的结构:
while( $row = mysqli_fetch_assoc( $result)){
$resguard[] = $row;
}
print_r($resguard);
这是(为清楚起见而格式化):
Array (
[0] => Array ( [id] => 1 [name] => Grandfather [parent_id] => )
[1] => Array ( [id] => 2 [name] => Parent [parent_id] => 1 )
[2] => Array ( [id] => 3 [name] => Uncle [parent_id] => 1 )
[3] => Array ( [id] => 4 [name] => Son [parent_id] => 2 )
[4] => Array ( [id] => 5 [name] => Brother [parent_id] => 2 )
[5] => Array ( [id] => 6 [name] => Sister [parent_id] => 2 )
)
解决方案
这是一个适用于您的数据集的示例,并假设原始数据按 id 排序(就像您的查询一样)。我相信要走的路是编写小(er)、简单(r)的函数,将数据转换成树并逐步遍历它。可能有可能从数组中进行遍历并像您一样一次飞跃地打印它,但是我的大脑目前无法想出一个好方法。
function make_tree($data) {
$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 preorder(&$root) {
if ($root) {
yield $root;
if (array_key_exists("children", $root)) {
foreach ($root["children"] as $c) {
yield from preorder($c);
}
}
}
}
$data = [
["id" => 1, "name" => "Grandfather", "parent_id" => null],
["id" => 2, "name" => "Father", "parent_id" => 1],
["id" => 3, "name" => "Uncle", "parent_id" => 1],
["id" => 4, "name" => "Son", "parent_id" => 2],
["id" => 5, "name" => "Brother", "parent_id" => 2],
["id" => 6, "name" => "Sister", "parent_id" => 2]
];
$tree = make_tree($data);
foreach (preorder($tree) as $node) {
echo $node["name"]."\n";
}
输出:
Grandfather
Father
Son
Brother
Sister
Uncle
推荐阅读
- azure-web-app-service - Azure 应用服务 (Linux) CI/CD 构建不会删除从存储库中删除的文件
- php - 循环请求中的偏移量和限制
- matlab - Matlab中多个变量的顺序求解方程
- java - 如何使这个线程安全?
- datetime - 如果取消选中复选框,如何使用 Google Sheets Apps 脚本清除单元格?
- git - 默认情况下,我们在 .git 中有隐藏文件吗?
- python - 为什么我的 pyqtgraph y 轴在 x 轴上方偏移?
- wordpress - 更改结帐页面运费总额
- r - 根据 R 中的几种模式拆分列
- php - 如何使推送通知将用户发送到应用程序中的特定页面?