Get all child, grandchild etc nodes under parent array using php with mysqli - Mostlikers

27 October, 2015

Get all child, grandchild etc nodes under parent array using php with mysqli

Today I have post Get all child, grandchild etc nodes under parent array using PHP with MySQL. I was recently working on an E-commerce project there I have to implement unlimited category along subcategory level drop down a list. I have inserted all the product category and subcategory in the single table to view drop-down list I have used this code.

Get all child, grandchild etc nodes under parent array using php with mysqli




Database

Create sample table name like 'menu_list'. Insert some sample data.
CREATE TABLE IF NOT EXISTS `menu_list` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(200) NOT NULL,
  `parent_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
)

Menu list table


PHP

<?php  
$menu['products'] =getChildren($parent_id="0");
echo '<pre>'; print_r($menu); // check tree array
function getChildren($parent_id)
{
  $db=new mysqli('localhost','root','','mostlikers'); //db
  $cat=$db->query("SELECT * FROM menu_list WHERE parent_id=$parent_id");
  $children = array();
  $i = 0;   
  foreach ($cat as $key => $cat_value) {
    $children[$i] = array();
    $children[$i]['name'] = $cat_value['name'];
    $children[$i]['children'] =getChildren($cat_value['id']);
    $i++;
  } 
  return $children;
} 
?>

getChildren - Based on the parent id fetch all the child, grandchild nodes.


"You have to dream before your dreams can come true."
                                             
                                         - A. P. J. Abdul Kalam








Related Topics

No comments:

Post a Comment