修改 foreach 循环以输出 <li> 基于 ID 变量


Amend foreach loop to output <li> based on variable of IDs

我正在尝试修改在Magento网站前端绘制类别列表的方式(简单的想法)。我有一个类别列表,我想将其与jquery手稿分开并使用,因此对于EG。我想要一个标题"2010 及更早版本",其下包含 ID 为 1 到 10 的类别。然后我想要一个标题"2011",在该标题下,ID 为 11 到 20 的实时类别。

下面的默认类别代码只是循环遍历 ID 并在<UL>中回显类别列表 - 但我想自定义<UL>

<?php $collection = $this->_getCollection(); ?>
<?php if (count($collection) > 0) : ?>

    <?php foreach ($collection as $_category ) : ?>            
                <li>
                    <a href="<?php echo $this->getUrl('gallery/category/view/', array('id' => $_category->getId())); ?>"><?php echo $this->htmlEscape($_category->getName()) ?></a>
                </li>
    <?php endforeach ?>
<?php endif; ?>

我看不到树木的木头! - 我想将 ID 拉入数组并根据 IF 语句绘制新结构,但在构建数组时没有运气。

任何人都可以看到一种快速的方法,我可以打破循环说,如果 ID 是 1 到 10,然后在 <li class="2010"> 中列出,然后继续 ID 11 到 20 <li class="2011">例如。?

非常感谢

尝试检查您不想显示的类别 ID,并使用continue;获取下一个:

<?php foreach ($collection as $_category ): ?>
<?php if ($_category->getId() == 10) { continue; } ?>
    <li>
        <a href="<?php echo $this->getUrl('igallery/category/view/', array('id' => $_category->getId())); ?>"><?php echo $this->htmlEscape($_category->getName()) ?></a>
    </li>
<?php endforeach ?>

你应该划分你的问题。一部分是输出,可以用一个函数来表示:

<?php
$htmlLi= function($class, $url, $name) {
?>
                <li class="<?php echo $class; ?>">
                    <a href="<?php echo $url; ?>"><?php echo $name; ?></a>
                </li>
<?php
}

然后你有逻辑根据某个id决定类名:

$classById = function($id) {
    $class = $id < 11 ? '2010' : '2011';
    return $class;
}

你最后想把这个放在一起:

<?php $collection = $this->_getCollection(); ?>
<?php if (count($collection) > 0) : ?>
    <?php foreach ($collection as $_category) {
        $id    = $_category->getId());   
        $class = $classById($id);
        $url   = $this->getUrl('gallery/category/view/', array('id' => $id);
        $name  = $this->htmlEscape($_category->getName());
        $htmlLi($class, $url, $name);
    } ?>
<?php endif; ?>

这也表明,你自己的函数_getCollection()还没有以你需要的格式返回数据。最好返回循环真正需要的字段:

$class, $url and $name