How To Get Sub Categories in Magento ?`

自闭症网瘾萝莉.ら 提交于 2019-12-03 20:30:23

Do this instead :

Mage::getModel('catalog/category')->load('23')->getChildrenCategories();

and iterate over the result.

and that's how i found it out:

$object = Mage::getModel('catalog/category'); 
print_r(get_class_methods($object));
print_r($object->load('23')->getChildrenCategories()->toArray());

Here's another way to do this, if you don't want to mess with the treeModel stuff, or want more control how categories are loaded:

function getCategoryTree($root_category_name)
{
    $categories = Mage::getModel('catalog/category')->getCollection()
        ->addAttributeToSelect("*")
        ->addFieldToFilter("Name",array("eq"=>$root_category_name));

    $stack = array();
    $category = $categories->getFirstItem()->getData();
    $categories=array();
    array_push($stack, $category);
    //regular recursion is boring, let's do a stack
    while(count($stack) > 0)
    {
        $category = array_pop($stack);
        array_push($categories, $category);
        $children = Mage::getModel('catalog/category')->getCollection()
            ->addAttributeToSelect("*")
            ->addFieldToFilter("parent_id",array("eq"=>$category['entity_id']))
            ->addAttributeToSort("position","desc");

        foreach ($children as $child)
        {
            array_push($stack, $child->getData());
        }
    }

    return $categories;
}

This will give you an array of categories representing the full category tree rooted at the top category with the name "Some Category Name", in order, with all of the category data. Tune this to only select the specific fields you need, instead of "*".

This technique can give you finer grained control of the loading of the category tree, and with how you want the data structured afterwards. For example, you could trivially modify this to do a hierarchical tree instead of a flat array and then serialize that to a JSON object to send to the client.

Add whatever filters you like (active, etc...) at whatever level you like to get even more control.

iterate through this object

Mage::getModel('catalog/category')
                    ->getCollection()
                    ->addAttributeToSelect('*')
                    ->getItems();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!