从magento中的Child类别生成树

时间:2012-05-07 13:02:48

标签: magento

category list

我有子类别名称及其ID

如图所示

前马扎里沙里夫和赫拉特

如何从子类别生成树,如图像???

所示

我想生成与图像相同的树

1 个答案:

答案 0 :(得分:1)

使用以下代码,它会对您有所帮助。

$_rootCatId     = 2;
$_rootCategory  = Mage::getModel('catalog/category')->load($_rootCatId);
$_catName       = $_rootCategory->getName();
if($_rootCategory->hasChildren()) 
{
$_collection = Mage::getResourceModel('catalog/category_collection')
                ->addAttributeToFilter('is_active', 1)
                ->addAttributeToSort('position', 'asc')
                ->joinUrlRewrite()
                ->addIdFilter($_rootCategory->getChildren())
                ->load();

foreach($_collection AS $_sub)
{
    $_subCat    = Mage::getModel('catalog/category')->load($_sub->getId());

    if($_subCat->hasChildren()) 
    {   
        echo '<li class="leve10 nav-'. $_subCat->getId() .'">';
            echo '<a id="subCatLink">';
                echo '<span>'. $this->htmlEscape($_subCat->getName()) .'</span>
                </a>
         </li>';
        echo '<ul id="subCatUl" style="padding:0px 13px;">';
        $__collection = Mage::getResourceModel('catalog/category_collection')
                ->addAttributeToFilter('is_active', 1)
                ->addAttributeToSort('position', 'asc')
                ->joinUrlRewrite()
                ->addIdFilter($_subCat->getChildren())
                ->load();

        foreach($__collection AS $__sub)
        {
            $__subCat   = Mage::getModel('catalog/category')->load($__sub->getId());
            echo '<li class="leve20 nav-'. $__subCat->getId() .'">
                    <a href="'. $this->getCategoryUrl($__subCat) .'">
                     <span>'. $this->htmlEscape($__subCat->getName()) .'</span>
                    </a>
                 </li>';
        }
        echo '</ul>';
    }
    else
    {
        echo '<li class="leve10 nav-'. $_subCat->getId() .'">
            <a href="'. $this->getCategoryUrl($_subCat) .'">
             <span>'. $this->htmlEscape($_subCat->getName()) .'</span>
            </a>
         </li>';
    }
}
}