How to display Multi Level Tree structure Category’s In PHP Using Recursive function.

  1. First let’s see the table structure for multilevel category
category_id : primary key
category_name : varchar
category_parent :  foreign key

2. Assuming You have done database connection

3) Create Recursive function

function catgeory_view($id=0) // Recursive function
{
  global $con;
  $select_category="SELECT * FROM store_categories WHERE category_parrent=$id order by category_order";
  $result_category=mysqli_query($con,$select_category);
  $output="";
  if($result_category)
  {
    $row_count=mysqli_num_rows($result_category);
    if($row_count>0)
    {
      $output.="<ul class='list-group'>";
      while($row_data=mysqli_fetch_array($result_category))
      {
            $output.="<li class='list-group-item'>".$row_data['category_name']."".catgeory_view($row_data['category_id'])."</li>"; 
      }
      $output.="</ul>";    
    }
    else 
    {
        $output.="<ul class='space'></ul>";
    }
  }
  return $output;
}

4. and now display Tree/Hierarchy structure category’s by calling Recursive Function

 <ul class="list-group">
               <?php
            $select_category="SELECT * FROM store_categories WHERE category_parent=0";
            $result_category=mysqli_query($con,$select_category);
            $output="";
            if($result_category)
            {
              $row_count=mysqli_num_rows($result_category);
              if($row_count>0)
              {
                while($row_data=mysqli_fetch_array($result_category))
                {
                    $output.= "<li class='list-group-item'  >".$row_data['category_name']."".catgeory_view($row_data['category_id'])."</li>";
                    
                }
              }
            }
            echo $output;
            ?>
           
          </ul>

Add a Comment

Your email address will not be published. Required fields are marked *