读书人

施用TreeNode方式输出指定查询条件的分

发布时间: 2012-12-18 12:43:41 作者: rapoo

使用TreeNode方式输出指定查询条件的分类
使用Category Collection手工构造sql输出制定查询条件的分类,效率低,代码复杂,本例介绍另一种方式

<?php   // initialize magento environment for 'default' store   require_once '../../app/Mage.php';   Mage::app('default');      function getStoreCategories($sorted=false, $asCollection=false, $toLoad=true) {      $parent = 6; // 6 是名字为'品牌'的类别id.      $category = Mage::getModel('catalog/category');      if (!$category->checkId($parent)) {         if ($asCollection) {            return new Varien_Data_Collection();         }         return array();      }      $recursionLevel = max(0, 0);      $tree = $category->getTreeModel();      $nodes = $tree->loadNode($parent)         ->loadChildren($recursionLevel)         ->getChildren();      $tree->addCollectionData(null, $sorted, $parent, $toLoad, true);      if ($asCollection) {         return $tree->getCollection();      } else {         return $nodes;      }   }   function getCategory($categoryNode){      $category = Mage::getModel('catalog/category');      $category->setData($categoryNode->getData());      return $category;   }   /*   *   Main Funtion   */   header("content-Type: text/html ; charset=utf-8");?><!-- 输出两层Category --><?php foreach (getStoreCategories() as $_categoryNode) { ?><div id="subcat1">   <?php $category =getCategory($_categoryNode); ?>   <h2 id="cat1">      <a href="<?php echo $category->getUrl(); ?>"><?php echo $category->getName(); ?>(<?php echo $category->getProductCount(); ?>)</a>   </h2>   <?php $hasChildren = $_categoryNode->hasChildren(); ?>   <?php if($hasChildren){         foreach ($_categoryNode->getChildren() as $subCategoryNode){         $subCategory =getCategory($subCategoryNode);   ?>      <a href="<?php echo $subCategory->getUrl(); ?>"><?php echo $subCategory->getName(); ?></a>   <?php         }      }   ?>   </div></div><?php   } ?>


代码范例中的getCategory方法是获得Node对应的Cateogry模型实例,目的仅仅是为了调用它的getUrl方法.

下面是我机器上的输出结果:

读书人网 >编程

热点推荐