This is my Code for creating n-level category.
function fetchCategoryTree($parent = 0, $spacing = '', $user_tree_array = '') {
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT `cat_id`, `cat_name`, `parent_id` FROM `category` WHERE `parent_id` = $parent ORDER BY cat_id ASC";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_object($query)) {
$user_tree_array[] = array("id" => $row->cat_id, "name" => $spacing . $row->cat_name);
$user_tree_array = fetchCategoryTree($row->cat_id, $spacing . ' -', $user_tree_array );
}
}
return $user_tree_array;
}
$categoryList = fetchCategoryTree();
Displaying all categories in drop-down
$id=$_GET['id'];
<td> Category:</td><td><select name="parentcat" id="parentcat" onchange="getText(this)">
<option selected value="Root">--Root Level--</option>
<?php
foreach($categoryList as $cl) {
?>
<option value="<?php echo $cl["id"] ?>"><?php echo $cl["name"]; ?></option>
<?php } ?>
Now I wanted to display selected parent name in dropdown. If a category name is Laptop it's parent name would be 'Electronics. I wanted Electronics to be showed up in dropdown.
My database would be like this:
cat_id | cat_name | parent_id ------------------------------- 1 | Electronics| 0 ------------------------------- 2 | Laptops | 1
I want this Electronics in dropdown If I select Laptops.