We help IT Professionals succeed at work.

Display Parent - Child (Hierarchy) using  Recurssion or Iteration

Sukhwinder Singh
on
Medium Priority
609 Views
Last Modified: 2007-12-19
I want to display parent child hierarchy on a web page using PHP.

I am using recursion for that but relationship is not being displayed correctly.

I have a table in database with 3 fields:

id, parent_id, name

child which doesn't have any parent has 0 as parent id.

So I call the below given function with id of 0 to start displaying hierarchy.

Parent and child are displayed in correct order but indenting by using "-" is not.

<?php
      $level = 1;
      function displayChildren($parent_id)
      {
            
            static $level;
            
            $query = "select * from categories where parent_id=$parent_id";
            $result = mysql_query($query)   or die(mysql_error());
            while ($row = mysql_fetch_array($result))
            {
                  
                                                
                  echo "<option value=\"". $row['id'] . "\">";
                  
                  echo $parent_id . " ". $row['id']. " ". $level;
                  for ($i=0; $i <= $level; $i++)
                  {                        
                        echo "-";
                  }
                  echo $row['name'] . "</option>";
                  $level += 1;
                  displayChildren($row['id']);
                  $level = 1;
            }
            
      }
?>

I have solved this problem by adding a new field in table called level which stores, at the time of addition, the level in the hierarchy a category has. For example if a parent has level of 4 then child will have level 5 and so on.
Problem is that when I change parent of a child level of all the children of this child also has to be changed.

I want a solution where no additional field "level" is stored in the table and level is determined at the time of displaying the hierarchy.

1. Is it possible to do it by using only one query and using recursion.
2. Is there any way to do it without recursion.
Comment
Watch Question

Commented:
You must use recursive.
There some algorithm dealing with tree structure.
You can use depth search first algorithm or breadth first search algorithm.

Author

Commented:
i am already doing depth first.
I thought static variable will work but it doesn't

Commented:
Try this

<?php
     function displayChildren($parent_id,$level)
     {
          $query = "select * from categories where parent_id=".$parent_id;
          $result = mysql_query($query)   or die(mysql_error());
          while ($row = mysql_fetch_array($result))
          {
               echo "\n<option value=\"". $row['id'] . "\">";
               
               echo $parent_id . " ". $row['id']. " ". $level;
               for ($i=0; $i <= $level; $i++)
               {                    
                    echo "-";
               }
               echo $row['name'] . "</option>";
               displayChildren($row['id'],($level+1));
          }
     }
      
       displayChildren(0,0);
?>

Commented:
Hi

It seems very silly to run a query over and over again! It would be better to GROUP/ORDER BY your results and then loop that (1) SQL query! Many times allowing SQL to handle your (?) is the best idea, but when your (?) makes unnecessary query's then it is not the best way to do it! Your result set with a single (1) query would have all the information to display it the way you want, because it would be GROUPED/ORDERED giving you a test mechanism to tell how to handle the current and next result set!


Not seeing your database layout or an example of a few rows and how you want it displayed, I can't give you the correct query to use or the code to display it!


Fataqui!

Author

Commented:
"Not seeing your database layout or an example of a few rows and how you want it displayed, I can't give you the correct query to use or the code to display it! "

There are just three columns in categories table.
Id, parent_id, name.

parent_id stores the parent of the selected category.
Top level category has 0 as its parent.  Sample rows:

id    parent_id      name
1    0                   Electronics
2    1                  Computers
3    1                 Televisions
4    2                  Dell

Now can you give me a query which will display the result I want like this:

None
-Electronics
--Computers
---Dell
--Televsions
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Ok I'll check the above query on Monday and reply.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.