magento 得到树形结构的分类列表

<?php
?>
<?php
 
class Lehui_AllCategoryList_Block_List extends Mage_Core_Block_Template
{
    
    protected $_store;
    protected $_baseUrl;
    
    protected function _construct(){
        parent::_construct();
        $this->_init();
    }
    
    protected function _init(){
        $this->_store=Mage::app()->getStore();
         $this->_baseUrl=Mage::getBaseUrl();
    }
    
    
    public function getAllCategory(){
        
        $parentId = 1;
        
        $tree = Mage::getResourceSingleton('catalog/category_tree')->load();
        $root = $tree->getNodeById($parentId);
        if($root && $root->getId() == 1) {
            $root->setName(Mage::helper('catalog')->__('Root'));
        }
        foreach(get_class_methods($tree) as $item){
           // echo $item,"</br>";
        }
        $collection = Mage::getModel('catalog/category')->getCollection()
                        ->addAttributeToSelect('name')
                        ->addAttributeToSelect('url_path')
                        ->addAttributeToSelect('path')
                        ->addAttributeToSelect('is_active')
                        ->addIsActiveFilter();
        //echo $collection->getSelectSql();//->addPathFilter('1\\/'.$this->_store->getRootCategoryId().'\\/')
        foreach(get_class_methods($collection) as $item){
            //echo $item,"</br>";
        }
        $tree->addCollectionData($collection, true);
        $root=$this->_nodeToArray($root);
        $this->_print_tree($root['children'],0);
    }
    
    
    protected function _print_tree($tree,$level){
        $level++;
        foreach($tree as $item){
            if($level>1&preg_match('/1\\/'.$this->_store->getRootCategoryId().'\\//',$item['path'])){
                echo str_repeat('&nbsp;&nbsp;', $level).'<a href="'.$item['url'].'">'.$item['name']."</a><br>";
            }
            $this->_print_tree($item['children'],$level); 
        }
    }
    
    
    protected function _nodeToArray(Varien_Data_Tree_Node $node){
        $result = array();
        $result['category_id'] = $node->getId();
        $result['parent_id'] = $node->getParentId();
        $result['name'] = $node->getName();
        $result['is_active'] = $node->getIsActive();
        $result['position'] = $node->getPosition();
        $result['level'] = $node->getLevel();
        $result['url']=$this->_baseUrl.$node->getData('url_path');
        $result['path']=$node->getData('path');
        $result['children'] = array();
        
        foreach ($node->getChildren() as $child) {
            $result['children'][] = $this->_nodeToArray($child);
        }
        
        return $result;
    }
    
    
    
}
posted @ 2015-09-14 23:18  幻星宇  阅读(189)  评论(0编辑  收藏  举报