Magento在模板中排序类别

时间:2012-03-07 09:57:17

标签: php arrays sorting magento object

我正在寻找一种方法来对导航中类别的前端显示进行排序。

这是我导航的代码:

<div id="menu-accordion" class="accordion">      
    <?php 

    foreach ($this->getStoreCategories() as $_category): ?>
    <?php $open = $this->isCategoryActive($_category) && $_category->hasChildren(); ?>
    <h3 class="accordion-toggle"><a href="#"><?php print $_category->getName();?></a></h3>
        <div class="accordion-content">
                <ul>
                <?php foreach ($_category->getChildren() as $child): ?>
                    <li> 
                        <span class="ui-icon ui-icon-triangle-1-e vMenuIconFloat"></span>
                            <a href="<?php print $this->getCategoryUrl($child); ?>"><?php print $child->getName();?></a>
                    </li>
                <?php endforeach; ?>
                </ul>
            </div>
    <?php endforeach ?>
</div>

我尝试使用asort()$this->getStoreCategories()进行排序,但它解决了错误500,所以我猜它不是一个数组,而是一个对象(对于magento的面向对象编程来说这似乎很明显) 。我试图找到一个对象的解决方案,但失败了,现在我有点卡住了。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

$this->getStoreCategories()的调用不会返回数组。但是你可以构建自己的数组并使用数组的键作为要排序的元素(假设你想按类别的名称排序):

foreach ($this->getStoreCategories() as $_category)
{
    $_categories[$_category->getName()] = $_category;
}

ksort($_categories);

现在,不是迭代$this->getStoreCategories()而是迭代$ _categories数组。所以你的代码看起来像是:

<div id="menu-accordion" class="accordion">      
    <?php 

    $_categories = array();
    foreach ($this->getStoreCategories() as $_category)
    {
        $_categories[$_category->getName()] = $_category;
    }
    ksort($_categories);

    foreach ($_categories as $_category): ?>
    <?php $open = $this->isCategoryActive($_category) && $_category->hasChildren(); ?>
    <h3 class="accordion-toggle"><a href="#"><?php print $_category->getName();?></a></h3>
        <div class="accordion-content">
                <ul>
                <?php foreach ($_category->getChildren() as $child): ?>
                    <li> 
                        <span class="ui-icon ui-icon-triangle-1-e vMenuIconFloat"></span>
                            <a href="<?php print $this->getCategoryUrl($child); ?>"><?php print $child->getName();?></a>
                    </li>
                <?php endforeach; ?>
                </ul>
            </div>
    <?php endforeach ?>
</div>