Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

How to create Multi Level Category Hierarchy using PHP(Recursive function) & Mysql

In this article we will create a multi-level category menu using PHP and mysql, by calling a recursive function, we can display infinite level of categories and subcategories.

Multi Level Category Hierarchy using PHP

Follow step by step instruction:

Download code

1) Create Database:
You need to create a Database 'multi_level' and a table 'category' with 3 columns as following:

category_id : Primary key.
category_name : Name of the category.
parent_id : It is the parent to corresponding category_id. For root category parent_id is 0.

2) Create Database connection:
<?php
DEFINE('DB_HOST','localhost');
DEFINE('DB_USER','root');
DEFINE('DB_NAME','multi_level');
DEFINE('DB_PASS','');
 

$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or 
      die('could not connect: '. mysqli_connect_error() );

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

3) Create mysql query to fetch data:
<?php 
$sql = "SELECT category_id, category_name, parent_id FROM category ORDER BY parent_id, category_id";
$results = mysqli_query($con,$sql) or die(mysqli_error()) ;
if($results)
{
    while($result = mysqli_fetch_array($results))
    {
        $category['categories'][$result['category_id']] = $result; 
        $category['parent_cats'][$result['parent_id']][] = $result['category_id']; 
    }
}
?>

4) Create Recursive function to display Category Hierarchy:
<?php 
function getCategories($parent, $category) 
{
    $html = "";
    if (isset($category['parent_cats'][$parent]))
    {
        $html .= "<ul>\n";
        foreach ($category['parent_cats'][$parent] as $cat_id)
        {
            if (!isset($category['parent_cats'][$cat_id]))
            {
              $html .= "<li>".$category['categories'][$cat_id]['category_name']."</li> \n";
            }
            if (isset($category['parent_cats'][$cat_id]))
            {
              $html .= "<li>". $category['categories'][$cat_id]['category_name'] . " \n";
              $html .= getCategories($cat_id, $category);
              $html .= "</li> \n";
            }
        }
        $html .= "</ul> \n";
    }
    return $html;
}
?>

5) Now call Recursive function to display all Category in Hierarchy:
<?php echo $data['category'] = getCategories(0, $category);?>
Please add your feedback!

Please support us, Like us on Facebook.

 

Copyright @ 2017 HKBlog.