我的数据库中有这些数据:
id nameOfPerson parent
3 John NULL
4 Michel 3
5 Husam 4
6 Khalaf 5
7 Mark 5
----------------------------
我想在列表中显示它
但在我的代码中他刚刚显示
我想如何根据上面列表中的父项删除所有数据?
这是我的功能是什么错误?
public function familyTree(){
$query = "SELECT id, nameOfPerson, parent FROM person WHERE parent is null";
$statment = $this->db->prepare($query);
$statment->execute();
echo '<ul id ="family">';
while($family = $statment->fetch(PDO::FETCH_OBJ)){
echo '<li>'. $family->nameOfPerson;
$query1 = "SELECT id, nameOfPerson, parent FROM person WHERE parent = :id";
$statment1 = $this->db->prepare($query1);
$statment1->bindValue('id', $family->id);
$statment1->execute();
if($statment1->rowCount() > 0){
echo '<ul>';
while($family2 = $statment1->fetch(PDO::FETCH_OBJ)){
echo '<li>' . $family2->nameOfPerson . '</li>';
}
echo '</ul>';
}
echo '</li>';
}
echo '</ul>';
}
答案 0 :(得分:1)
<强>的假设强>
1
父母。<强> CODE 强>
首先,我从数据库表中检索所有数据,因为无法为每个增加数据库调用的父项单独检索数据并影响响应时间。
建立一个父和子的关联数组,其中每个父级都有each child
- nameOfPerson
和id
的2个详细信息。
以递归方式迭代此数组并继续为每个子项构建列表并最终返回它们。
请参阅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>