Reputation: 69
i'm trying to output the children data from database of a particular parent using the parent id to a genealogy tree.
i'm new to php, but i have been able to get to display the whole tree starting from the top.
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>";
}
}
and this to get result
printList();
id | parent id | name |
1 | 0 | 1st user |
2 | 1 | 2nd user |
3 | 1 | 3rd user |
4 | 1 | 4th user |
6 | 2 | 5th user |
7 | 2 | 6th user |
8 | 2 | 7th user |
such that if i want to get all the children of 2nd user, i should get 5th, 6th and 7th user. And i 1st user would have 2nd, 3rd and 4th user as children and 5th, 6th and 7th as grand children.
Upvotes: 1
Views: 723
Reputation: 72299
Please check this url:-Why shouldn't I use mysql_* functions in PHP?
And solution for current problem is:-
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;
}
Upvotes: 0