magento - 检索给定类别ID的所有子类别

Luk*_*uke 2 php magento magento-1.4 magento-1.5

如标题中所述,我正在尝试通过我的自定义函数来完成这些工作:

public function retrieveAllChilds($id = null, $childs = null){

        $childIdsArray = is_null($childs) ? array() : $childs;
        $category = is_null($id) ? $this->getCurrentCategory() : $this->getCategoryFromId($id);
        if (count($this->getChildrenCategories($id)) > 0) {
            $c = count($this->getChildrenCategories($id));
            $tmp_array = array();
            foreach ($this->getChildrenCategories($id) as $category) {
                array_push($tmp_array, $category->getId());             
            }
            $childIdsArray = array_merge($childIdsArray, $tmp_array);
            foreach ($this->getChildrenCategories($id) as $category){
                $this->retrieveAllChilds($category->getId(), $childIdsArray);
            }
        }
        else{
            return array_unique($childIdsArray);
        }

        return array_unique($childIdsArray);
}
Run Code Online (Sandbox Code Playgroud)

但似乎在停止或退出条件下出现了问题.该函数正确检索前16个元素.有人可以帮我吗?

Sim*_*mon 8

我认为该课程Mage_Catalog_Model_Category已包含您正在搜索的功能.它被称为getChildren:

public function retrieveAllChilds($id = null, $childs = null) {
    $category = Mage::getModel('catalog/category')->load($id);
    return $category->getChildren();
}
Run Code Online (Sandbox Code Playgroud)

该函数getChildren返回以逗号分隔的子ID,getChildrenCategories返回Mage_Catalog_Model_Category实例数组.

如果要以递归方式获取子类别,可以使用:

public function retrieveAllChilds($id = null, $childs = null) {
    $category = Mage::getModel('catalog/category')->load($id);
    return $category->getResource()->getChildren($category, true);
}
Run Code Online (Sandbox Code Playgroud)

  • 你是完全正确的,除了默认情况下它不会递归地获取它们(所以只有顶级).他会想要使用:$ category-> getResource() - > getChildren($ category,true); (3认同)