Solved

Display Parent - Child (Hierarchy) using  Recurssion or Iteration

Posted on 2004-04-10
10
577 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Google maps, choose location using pin 10 23
sql sentence 2 13
Adding through query php 9 12
showing numeric numbers 2 11
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
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 …

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now