首页 > 解决方案 > 如何获取特定父级(父级 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 个作为孙子。

标签: phpmysql

解决方案


请检查这个网址:-为什么我不应该在 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;
}

推荐阅读