使用while循环限制PHP的结果

时间:2012-07-19 17:01:22

标签: php

我有一个返回的子类别列表。我只能访问模板显示而不是MySQL查询,所以不,我不能限制查询。

现在返回所有结果。我想将列表限制为5,如果结果超过5,则添加“更多”链接。

我知道我做错了,因为我认为count实际上与foreach无关:

<ul class="sub-categories">
    <?php
    while (count($category->getChildren()) <= 5) { // line I added for while loop
        foreach ($category->getChildren() as $child) {
            if (!$child->totalItemCount())
                continue;

            $link = $this->app->route->category($child);
            $item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
                echo '<li><a href="'.$link.'" title="'.$child->name.'">'.$child->name.'</a>'.$item_count.'</li>';
        }
    } // line I added for while loop
    ?>
</ul>

1 个答案:

答案 0 :(得分:1)

当您达到限制时,在foreachbreak;内跟踪:

<ul class="sub-categories">
    <?php
        $i = 0;
        foreach ($category->getChildren() as $child) {
            if (!$child->totalItemCount()) continue;
            $i++; if($i>5) break;
            $link = $this->app->route->category($child);
            $item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : '';
            echo '<li><a href="'.$link.'" title="'.$child->name.'">'.$child->name.'</a>'.$item_count.'</li>';
        }
    ?>
</ul>