Solved

Display Parent - Child (Hierarchy) using  Recurssion or Iteration

Posted on 2004-04-10
10
587 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.
0
Comment
Question by:Sukhwinder Singh
10 Comments
 

Expert Comment

by:dodyrw
ID: 10796366
You must use recursive.
There some algorithm dealing with tree structure.
You can use depth search first algorithm or breadth first search algorithm.
0
 

Author Comment

by:Sukhwinder Singh
ID: 10796407
i am already doing depth first.
I thought static variable will work but it doesn't
0
 

Expert Comment

by:thaak
ID: 10796572
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 2

Expert Comment

by:Fataqui
ID: 10797521
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
 

Author Comment

by:Sukhwinder Singh
ID: 10797956
"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
 
LVL 5

Accepted Solution

by:
TheClickMaster earned 125 total points
ID: 10797973
<?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
 

Author Comment

by:Sukhwinder Singh
ID: 10798051
Ok I'll check the above query on Monday and reply.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question