使用递归函数从Magento打印出一个嵌套的类别列表


Printing out a nested list of categories from Magento using a recursive function

所以我在/[my-theme-name]/template/catalog/navigation/left中有以下代码。php作为概念的证明:

<?php
$Mage_Catalog_Block_Navigation = new Mage_Catalog_Block_Navigation();
$categories = $Mage_Catalog_Block_Navigation->getStoreCategories();
function render_flat_nav($categories) {
    $html = '<ul>';
    foreach($categories as $category) {
        $html .= '<li><a href="' . $category->getCategoryUrl($cat) . '">' . 
                  $category->getName() . "</a>'n";
        if($category->hasChildren()) {
            $children = $category->getChildren();
            $html .= render_flat_nav($children);
        }
        $html .= '</li>';
    }
    return $html . '</ul>';
}
echo render_flat_nav($categories); ?>

对于第0级和第1级的类别,它工作得很好,但是任何嵌套更深的类别都不会被打印出来。

所以$category->getChildren()不能完全返回我期望的结果。有没有一种方法可以用来处理递归函数?

我已经找到了这个问题的答案,但它可能是次优的:

<?php
$Mage_Catalog_Block_Navigation = new Mage_Catalog_Block_Navigation();
$categories = $Mage_Catalog_Block_Navigation->getStoreCategories();
function render_flat_nav($categories) {
    $html = '<ul>';
    foreach($categories as $category) {
        $html .= '<li><a href="' . $category->getCategoryUrl($cat) . '">' . 
                  $category->getName() . "</a>'n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->entity_id);
            $html .= render_flat_nav($children);
            }
        $html .= '</li>';
    }
    return $html . '</ul>';
}
echo render_flat_nav($categories); ?>
$_category = Mage::getModel('catalog/category')->load(257);    
         $_categories = $_category
                    ->getCollection()
                    ->addAttributeToSelect(array('name', 'image', 'description'))
                    ->addIdFilter($_category->getChildren());
function render_flat_nav($categories) {
    $html = '<ul>';
    foreach($categories as $category) {
        $html .= '<li><a href="' . $category->getCategoryUrl($cat) . '">' . 
                  $category->getName() . "</a>'n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->entity_id);
            $html .= render_flat_nav($children);
            }
        $html .= '</li>';
    }
    return $html . '</ul>';
}
echo render_flat_nav($_categories);

多亏了上面的内容,我成功地让它适用于特定的类别id,这也适用于平面类别。