require_once(“app/Mage.php”);
umask(0);
Mage::app();
$_helper = Mage::helper(‘catalog/category’);
$_categories = $_helper->getStoreCategories();
$cats = array();
function getCats($_categories)
{
    global $cats;
    foreach ($_categories as $_category) {
        if($_category->getIsActive()) {
            $cats[$_category->getId()] = $_category->getName();
            $childCats = $_category->getChildrenCategories();
            if (count($childCats) > 0) getLowestCats($childCats);
        }
    }
}
getCats($_categories);
ksort($cats);
foreach ($cats as $k => $aCat) {
    echo “(“.$k.”) “.$aCat.”<br>\n”;
}

1 Answers

The categories and subcategories  as a DOM tree, and returns a descriptive associative array:-
require_once(“app/Mage.php”);
umask(0);
Mage::app();
 
function getChildCategories($category, $isFirst = false) {
 
        $children = $isFirst ? $category : $category->getChildren();
        // For each category, fetch its children recursively
        foreach ($children as $child) {
                $_categories[] = [ “name” => $child->getName(), “id” => $child->getId(), “children” => getChildCategories($child) ];
        }
        // Return our tree
        return $_categories;
};
 
// for rendering:
function renderCategoriesTree($category, $isFirst = false) {
        $children = $isFirst ? $category : $category->getChildren();
        echo “<ul>”;
        // For each category, fetch its children recursively
        foreach ($children as $child) {
                echo “<li>”; echo $child->getName(); echo “</li>”;
                renderCategoriesTree($child);
        }
        echo “</ul>”;
}
 
$_categories = Mage::helper(‘catalog/category’)->getStoreCategories();
// var_dump to see an associative array of all categories
$categories = getChildCategories($_categories, true);
// Run this to echo out a DOM
renderCategoriesTree($_categories, true);
 

Please login or Register to submit your answer
Not the answer you are looking for? Browse other questions tagged or ask your own question.