我正在尝试使用父 ID 将特定父级数据库中的子级数据输出到家谱树中。
我是PHP的新手,但是我已经能够从顶部开始显示整个树。
function getChildren($parent) {
$query = "SELECT * FROM member_log WHERE parent_id = $parent";
$result = mysql_query($query);
$children = array();
$i = 0;
while($row = mysql_fetch_assoc($result)) {
$children[$i] = array();
$children[$i]['username'] = $row['username'];
$children[$i]['children'] = getChildren($row['id'] );
$i++;
}
return $children;
}
$finalResult = getChildren('0');
function printList($array = null) {
if (count($array)) {
echo "<ul>";
foreach ($array as $item) {
echo "<li>";
echo "<a href= "#"> " . $item['username'] . "</a>";
if (count($item['children'])) {
printList($item['children']);
}
echo "</li>";
}
echo "</ul>";
}
}
而这要得到结果
printList();
身份证 | 家长编号 | 姓名 |
1 | 0 | 第一个用户 |
2 | 1 | 第二个用户 |
3 | 1 | 第三个用户 |
4 | 1 | 第四位用户 |
6 | 2 | 第 5 个用户 |
7 | 2 | 第 6 位用户 |
8 | 2 | 第 7 位用户 |
这样,如果我想获取第 2 个用户的所有子用户,我应该获得第 5、第 6 和第 7 个用户。我的第一个用户将有第二个、第三个和第四个用户作为孩子,第五、第六和第七个用户作为孙子。
请检查此网址:-为什么我不应该在PHP中使用mysql_*函数?
当前问题的解决方案是:-
function getChildren($parent) {
$query = "SELECT * FROM member_log WHERE parent_id = $parent";
$result = mysql_query($query);
$children = array();
while($row = mysql_fetch_assoc($result)) {
$children[$row['id']]['username'] = $row['username'];
$children[$row['id']]['children'] = getChildren( $row['id'] );
}
return $children;
}