php - 如何获取特定父级(父级 ID)的子级并在族谱树中显示输出
问题描述
我正在尝试使用父 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 | 第 4 位用户 |
6 | 2 | 第 5 位用户 |
7 | 2 | 第 6 位用户 |
8 | 2 | 第 7 位用户 |
这样,如果我想获得第二个用户的所有孩子,我应该获得第五个、第六个和第七个用户。我的第一个用户将有第 2、第 3 和第 4 个用户作为孩子,第 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;
}
推荐阅读
- node.js - 使用 AWS Amplify 并保护 GraphQL API 调用
- reactjs - 使用 Reactstrap 响应式表的带有固定标题的可滚动表
- laravel - 使用 laravel 和 vue js 从数据库中获取文件
- sas - 如何使用 SAS 从特定行中获取第一个和最后一个 MISSING 值
- ctypes - Python ctypes将指针传递给可变指针
- python - 如何使用缩写语法在 Django Serializer 中显示所有字段,包括相关字段?
- python - XACML 可以通过 Python 中的 lxml 进行验证吗?
- jdbc - 在应用程序中打包外部 jdbc 驱动程序以在 JBoss 中使用
- html - Flex由于某种原因没有垂直对齐?
- r - ggplot 没有分开地块