假设
代码
-
首先,我从DB表中检索所有数据,因为对于每个增加DB调用并影响响应时间的父级,单独检索数据是不高效的。
-
构建父级和子级的关联数组,其中每个父级有2个详细信息
each child
-
nameOfPerson
和
id
.
-
参考
SQL Fiddle
用于表格行。
<?php
$pdo = new PDO("mysql:dbname=newdummy;host=localhost","root","");
$query = $pdo->query("Select * from hierarchy");
$family_tree = [];
$root_parent = -1;
$root_parent_name = "";
function makeTree($query,&$family_tree,&$root_parent,&$root_parent_name){
while($row = $query->fetch(PDO::FETCH_ASSOC)){
if(is_null($row['parent'])){
$root_parent = $row['id'];
$root_parent_name = $row['nameOfPerson'];
}else{
if(!isset($family_tree[$row['parent']])){
$family_tree[$row['parent']] = [];
}
$family_tree[$row['parent']][] = array($row['nameOfPerson'],$row['id']);
}
}
}
function buildList($family_tree,$parent){
$list = "<ul>";
foreach($family_tree[$parent] as $each_child){
$list .= "<li>" . $each_child[0];
if(isset($family_tree[$each_child[1]])){
$list .= buildList($family_tree,$each_child[1]);
}
$list .= "</li>";
}
$list .= "</ul>";
return $list;
}
makeTree($query,$family_tree,$root_parent,$root_parent_name);
echo "<ul>";
echo "<li>$root_parent_name";
echo buildList($family_tree,$root_parent);
echo "</li>";
echo "</ul>";
产量
<ul>
<li>John
<ul>
<li>Michel
<ul>
<li>
Husam
<ul>
<li>khalaf</li>
<li>Mark</li>
</ul>
</li>
</ul>
</li>
<li>Tross</li>
<li>David</li>
</ul>
</li>
</ul>