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 mysqli. I was recently working on a E-commerce project there i have implement unlimited category along sub category level drop down list. I have insert all the product category and sub category in 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, grand child nodes.


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








Related Topics

No comments:

Post a Comment