我正在尝试使用父代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();
id |家长编号|名称|
1 | 0 |第一位用户|
2 | 1 |第二位用户|
3 | 1 |第三用户|
4 | 1 |第四位用户|
6 | 2 |第五位用户|
7 | 2 |第六位用户|
8 | 2 |第七位用户|
这样,如果我想获得第二个用户的所有子级,我应该获得第5个,第6个和第7个用户。我的第一个用户将把第二,第三和第四用户作为孩子,第五,第六和第七作为大孩子。
答案 0 :(得分:0)
请检查以下网址:-Why shouldn't I use mysql_* functions in PHP?
当前问题的解决方案是:-
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;
}