Create Parent/Child Tree Category in PHP and MySQL

Leave a Comment
I found this very cool code that I was searching for a long time. It’s about create a Parent and Child Tree Category. A scenario is something like Parent Category has a child category at the same time the child category also has a child category, so it’s like a category has an unlimited subcategory.

For example,
PHP
--Joomla
--Codeigniter

Here’s how to implement that one.
public function createCategoryTree($res, $parent, $cl = 0)
{
static $cat_tree = array("0"=>"None");
foreach($res as $key=>$val)
{
if($val->parent_id == $parent)
{
if($cl > 0)
{
$count = $cl; $dash = '';
while($count != 0)
{
$dash .= '-'; # Replace '-' with your delemiter to represent parent child relationship.
$count--;
}
$cat_tree[$val->category_id] = $dash.$val->category_name;
}
else
$cat_tree[$val->category_id] = $val->category_name;
$cl++;
createCategoryTree($res, $val->category_id, $cl); # Recursive Function...
$cl--;
}
}
return $cat_tree;
}
# Now fetch data from db using mysql_query() and mysql_fetch_assoc().
$cat_tree = createCategoryTree("Your data", 0);
In this function pass your array which contain category data as first argument. In second argument pass parent id. Basically it shoud be 0. Third argument is optional.(Default 0). Third argument work as level.

Note : Replace $category_id, parent_id and category_name accroding to your database fileds.
You can use this piece of code in any php framework also.

I hope this article is helpfut to you. And also share with your friends. 

0 comments:

Post a Comment