使用while循环限制PHP中的结果


Limit results in PHP using while loop

我有一个返回的子类别列表。我只能访问模板显示,不能访问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>

当您达到限制时,在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>