Posted by Thurein on 21st May 2010

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:

idnamep_id
1Main Parent0
2Sub Parent1
3Child2
4Parent 20
5Child 24
6Child 34
7Child 45

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)

  • About Thurein Soe
    Visit Thurein's website.

    Freelance Web Developer. Founder of The Tech Space. Follow me on Twitter.

    1. 12 Responses

    2. Bsd says:

      Hi,
      This worked nice! but how to work this with combo box menu ? (dropdown)
      thanks

    3. ndhol says:

      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

    4. Thurein says:

      Hi, BSD
      You just need to replace line no 7.

          echo str_repeat('-',$level)." ".$row['name']."<br />";
      

      With

      echo '<option value="'.$row['id'].'">'.str_repeat('-',$level).$row['name'].'</option>';
      

      So, the usage is

          <select name="category">
              <?php display_child(0,0); ?>
          </select>
      

      That’s it.

    5. Thurein says:

      Hi , ndhol
      You just need to add tags in function.
      Maybe, you may need some more parameter to pass and some if else condition.

    6. GBS says:

      Hi,
      nice scripts, how can i indent the sub categories or sub child in dropdown

      thanks

    7. Thurein says:

      Hi, GBS.
      I m sorry.
      Could u tell me more detail?
      My understanding is ur question is same with BSD comment?

    8. Janess says:

      It’s rlelay great that people are sharing this information.

    9. Dr Spock says:

      Hey man, thanks a lot… your code was really helpful (:

    10. Kadrwa Badam says:

      Can you have some words on formation of this parent -> child tree?

    11. verb8 says:

      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?

    12. Thurein says:

      Thanks for your comment.. I will improve it..

    Post your comments