Display Parent - Child (Hierarchy) using Recurssion or Iteration

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.
Sukhwinder SinghAsked:
Who is Participating?
 
TheClickMasterCommented:
<?php

// parameters
// 1= the value of the parent field of those who have no parents
// 2= always 0, is used for recursion
function display_user($name,$level)
{
      // some customizations---------------------------
      // the offset for a child node
      $offset = 2;
      // what we use as space
      $space = "&nbsp;";
      // horizontal line
      $char = "-";
      // vertical line
      $bar = "|";
      // node
      $node = "+";
      // ----------------------------------------------
      
      $prefix = "";
      
      for ($n = 0; $n < ($level*$offset); $n ++)
      {
            if ($n % $offset == 0)
            {
                  $prefix .= $bar;
            }
            if (($n + $offset) == ($level*$offset))
            {
                  $space = $char;
            }
            $prefix .= $space;
      }

      $Query  = "SELECT username as `name` FROM mytable ";
      $Query .= "WHERE parent=".$name." ";
      $Query .= "GROUP BY username ORDER BY username";
      $Result = mysql_query($Query) or die('SQL Error!<br>'.mysql_error());

      if (mysql_num_rows($Result) > 0)
      {
            $prefix .= $node;
      }
      else
      {
                  $prefix .= $char;
      }

      if ($level > 0)
      {
            echo $prefix."".$name."<br>\r\n";
      }
      
      while ($data = mysql_fetch_array($Result))
      {      
            display_user($data["name"],($level + 1));
      }
}

function ShowTree()
{
      // use a courier font to display it properly
      echo '<font face="Courier New" size="2">';
      // parameters
      // 1= the value of the parent tag of those who have no parents
      // 2= always 0, is used for recursion
      display_user(0,0);
      echo '</font>';
}

?>
0
 
dodyrwCommented:
You must use recursive.
There some algorithm dealing with tree structure.
You can use depth search first algorithm or breadth first search algorithm.
0
 
Sukhwinder SinghAuthor Commented:
i am already doing depth first.
I thought static variable will work but it doesn't
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
thaakCommented:
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);
?>
0
 
FataquiCommented:
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!
0
 
Sukhwinder SinghAuthor 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
0
 
Sukhwinder SinghAuthor Commented:
Ok I'll check the above query on Monday and reply.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.