How to display subcategories hierarchically from selected category?

Hi all !

I want to display hierarchical subcategories from a selected category.

So I have a query like folowing for listing all categories hierarchicaly, is it possible to create a function on same query instead of creating second query ?

Here is my query :

$sql = "SELECT * FROM categories";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$allCategories = array();
$categoryMulti = array(
    'categories' => array(),
    'parent_cats' => array()
);
while ($row = $stmt->fetch()) {
    //I created another array to get subcats didnt work
    //$categories['categories'][1]
    $categoryMulti['categories'][$row['cat_id']] = $row;
    $categoryMulti['parent_cats'][$row['parent_id']][] = $row['cat_id'];
    $allCategories[] = $row;
}

And this is the function listing all categories :

function listCategoryTree($parent, $category)
{
    $html = "";
    if (isset($category['parent_cats'][$parent])) {
        $html .= "<ul>\n";
        foreach ($category['parent_cats'][$parent] as $cat_id) {
            if (!isset($category['parent_cats'][$cat_id])) {
                $html .= "<li>" . $category['categories'][$cat_id]['cat_name'] . "</li>";
            } else {
                $html .= "<li>" . $category['categories'][$cat_id]['cat_name'];
                $html .= listCategoryTree($cat_id, $category);
                $html .= "</li>";
            }
        }
        $html .= "</ul> \n";
    }
    return $html;
}
echo listCategoryTree(0, $categoryMulti);

I would like to create another function on same query to display subCategories under selected category, if category.php?id=100 is clicked then I can display all subCategories belong to 100 in landing page.

I would like to use minimal queries in site, its why dont want to create second query if its possible.

Thanks for any help

I don’t think you need to create a NEW function to show child items to the page being viewed. I used a sample menu with your query and code and it produced the menu wonderfully. Note all main categories have a parent_id of 0 so for full menu I entered 0.

echo listCategoryTree(0, $categoryMulti);


If I were on any main category page, for example “Info” (which is cat_id 4) and called the function with this number only those children are shown.

echo listCategoryTree(4, $categoryMulti);

menu2
If I am on a first child level such as “Carpentry” (which is cat_id 8), the children under Carpentry are shown.

echo listCategoryTree(8, $categoryMulti);

menu3
If I go even deeper into the menu to “Colors”, those children are shown.

echo listCategoryTree(33, $categoryMulti);

menu4
So I guess you’ve got things covered already!

1 Like

Thank you so much Drummin! I was trying with new arrays which wasnt working :slight_smile:

That was what I wanted and function was created for that exactly, but I was falling on easy part calling it :slight_smile: Thanks again.