문제

Ok, the code I have written below works great, however I have some pages that may hit a few hundred categories and I do not want to ping the database every time through the foreach loop. Basically looking for a better way to handle the collection. Secondly, is there a way I can verify that this category is active.

<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>
도움이 되었습니까?

해결책

if you have a look at the code getStoreCategories calls a little down the line it uses Mage_Catalog_Model_Resource_Category_Tree. Perhaps you can use it yourself like this:

<?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
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top