Get Unlimited Parent and Child in PHP
Well, let me ask you first. Have you already known about recursion? If not, recursion mean reuse function in this function.
How is it ? For eg Like
function one_function ($var){
one_function(332);
}
OK , So , how to related with this post title ? I would like to say absolutely related with recursion. Let’s say, we would like to create category with parent and child.so, we have one table in database, category table. Table Structure Like:
| id | name | p_id |
|---|---|---|
| 1 | Main Parent | 0 |
| 2 | Sub Parent | 1 |
| 3 | Child | 2 |
| 4 | Parent 2 | 0 |
| 5 | Child 2 | 4 |
| 6 | Child 3 | 4 |
| 7 | Child 4 | 5 |
So, now I have created one table. I would like to get the out put like:
Main Parrent
- Sub Parent
– Child of sub parent
Parent 2
- Child 2
– Child of child 2
- Child 3
So, how will you do it? How could we get it?
If you write the codes like, for eg :
$result = mysql_query ();
while ( $row = mysql_fetch_assoc($result) ){
echo $row[name];
$result = mysql_query ();
while ( $row = mysql_fetch_assoc($result) ){
echo '- '.$row[name];
}
}
It would be work. But. If you have 3 or 4 or 5 levels and so on, you will got the trouble. So, what is the better way for that table? Shell we use recursion ?
I have written some code snippets like :
function display_child($parent, $level)
{
$sql = "SELECT * from `category` WHERE p_id='$parent'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo str_repeat('-',$level)." ".$row['name']."<br />";
display_child($row['id'], $level+1);
}
}
Usage – display_child( parent_id, level )
display_children(0,0);
I hope it would be useful for some of your projects. Enjoy !!!!
Download Source ( size 1.1 kB)
- Tutorials
Filed Under
-
Hi,
This worked nice! but how to work this with combo box menu ? (dropdown)
thanks -
Hi….it’s a nice script. I’d like to ask, how if we combine with syntax like and , because I want to combine with superfish jquery. Thx
-
Hi,
nice scripts, how can i indent the sub categories or sub child in dropdownthanks
-
[...] And I'm getting there with major help from the post here: http://www.thetechspace.com/2010/05/21/get-unlimited-parent-and-child-in-php. [...]
-
It’s rlelay great that people are sharing this information.
-
Hey man, thanks a lot… your code was really helpful (:
-
Can you have some words on formation of this parent -> child tree?
-
You do realize that this function will do enormous amount of database queries if your tree is decently big enough? (and it will be in time)
Sometimes recursion is a good solution, but your implementation simply sucks. It is wrong way of thinking. In this case, you successfully raped off your database server with tons of queries for the same “tree”.
Why not QUERY ONCE the table, and recursively build the tree from the result object/array?
Made by Symmetric Web
Distributed by Smashing Magazine
Freelance Web Developer. Founder of The Tech Space. Follow me on Twitter.