Aibol Orazbekov Aibol Orazbekov - 1 month ago 20
MySQL Question

Display subcategories and add classess to lists during recurion in PHP

I am using recursion function to display categories and subcategories in PHP.
In mysql database table, there are 3 columns:

cat_id, parent_id, cat_name


However, i should be keep tracking of unordered lists in order ot add class to make a drop down menu using Jquery. So, the html code should look like this:

<ul>
<li class = "dropdown"><a href = "#">Parent 1</a>
<ul class = "sub-menu">
<li><a href = "#">Sub 1</a></li>
<li class = "dropdown"><a href = "#">Sub 2</a>
<ul class = "sub-menu">
<li><a href = "#">Sub 2.1</a></li>
<li><a href = "#">Sub 2.2</a></li>
<li><a href = "#">Sub 2.3</a></li>
</ul>
</li>
<li><a href = "#">Sub 3</a></li>
<li><a href = "#">Sub 4</a></li>
<li><a href = "#">Sub 5</a></li>
</ul>
</li>
<li><a href = "#">Parent 2</a></li>
<li><a href = "#">Parent 3</a></li>
<li><a href = "#">Parent 4</a></li>




The recursion function that i am using:

$query = "select * from categories";$result = $conn->query($query); $cats = array();while($cat = $result->fetch_assoc()){$cats_ID[$cat['cat_id']][] = $cat;$cats[$cat['parent_id']][$cat['cat_id']] = $cat;}


function build_tree($cats,$cat_id,$only_parent = false){
if(is_array($cats) and isset($cats[$cat_id])){
$tree = "<ul>\n";
if($only_parent==false){
foreach($cats[$cat_id] as $cat){
$tree .= '<li><a href = "#">'.$cat['cat_name'];
$tree .= build_tree($cats,$cat['cat_id']);
$tree .= "</a></li>\n";
}
}
$tree .= "</ul>";
}
else return null;
return $tree;}


How can i keep track of ul lists?

Answer

This should do it like I suggested in the comment above by adding a $depth parameter.

$query = "select * from  categories";
$result = $conn->query($query);
$cats = array();
while($cat = $result->fetch_assoc()){
    $cats_ID[$cat['cat_id']][] = $cat;
    $cats[$cat['parent_id']][$cat['cat_id']] = $cat;
}

//added a depth argument that defaults to 1
function build_tree($cats,$cat_id,$only_parent = false, $depth=1){
    if(is_array($cats) and isset($cats[$cat_id])){
        //check if depth is > 1, output class, else, no class.
        if($depth > 1){
            $tree = "<ul class='sub-menu'>\n";
        } else {
            $tree = "<ul>\n";
        }

        if($only_parent==false){
            foreach($cats[$cat_id] as $cat){
                $tree .= '<li><a href = "#">'.$cat['cat_name'];
                //adjusted recursive call to include depth+1.
                $tree .=  build_tree($cats,$cat['cat_id'],$only_parent,$depth+1);
                $tree .= "</a></li>\n";
            }
        }
        $tree .= "</ul>";        
    }
    else return null;
    return $tree;
}

You should be able to just replace your function with this new one and everything should just work since the newly added argument has a default value.

Comments