Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Display Parent - Child (Hierarchy) using  Recurssion or Iteration

Posted on 2004-04-10
10
Medium Priority
?
592 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 500 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

618 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