好吧,我在下面编写的代码效果很好,但是我有一些页面可能会达到几百个类别,我不希望每次都通过foreach循环ping数据库。基本上寻找更好的方式来处理集合。其次,有没有办法可以验证此类别是否有效。我问了一个问题,以提高我的编程能力。所以请不要downvote ...
<ul>
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php foreach($_categories as $_category): ?>
<?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
<?php $_subcategories = $_category->getChildrenCategories() ?>
<?php foreach($_subcategories as $_subcategory): ?>
<li><a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"><?php echo $_subcategory->getName() ?></a></li>
<?php endforeach; ?>
<?php endforeach; ?>
</ul>
答案 0 :(得分:1)
如果你看一下代码,那么getStoreCategories会调用它使用Mage_Catalog_Model_Resource_Category_Tree
的行。也许你可以这样自己使用它:
<?php
require_once('app/Mage.php');
Mage::app();
$parent = Mage::app()->getStore()->getRootCategoryId();
$recursionLevel = 2;
$tree = Mage::getResourceModel('catalog/category_tree');
/* @var $tree Mage_Catalog_Model_Resource_Category_Tree */
$nodes = $tree->loadNode($parent)
->loadChildren($recursionLevel)
->getChildren();
$tree->addCollectionData(null, false, $parent);
foreach ($nodes as $node) {
/** @var $node Varien_Data_Tree_Node */
print_r($node->getData()); // first level category data
foreach ($node->getChildren() as $childNode) {
print_r($childNode->getData()); // second level category data
}
}