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 wrote some code snippets like :

function display_child($parent, $level) {

		$content= array();
		$sql = "SELECT * from test WHERE p_id='$parent'";
		$result = mysql_query($sql);
	   	while ($row = mysql_fetch_array($result)) {
		   	array_push($content,$row['id']);

			if (in_array($parent, $content)){
				echo $row['name']."
";

			}

			echo str_repeat('-',$level)." ".$row['name']."
";
			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 2.7 kB)

  • About Thurein Soe
    Visit Thurein's website.

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

  • No comments yet!

    Post your comments