0

I have a list of returned subcategories. I only have access to the template display and not to the MySQL query so no, I can't limit the query.

Right now all the results are returned. I would like to limit the list to 5, and then add a "more" link if there are more than 5 results.

I know I did this wrong because I don't think count is actually tied to the 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 Answer 1

1

Keep track within the foreach and break; when you've reached the limit:

<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>
Sign up to request clarification or add additional context in comments.

4 Comments

which is considered "better form" and why?
normally I would use a for loop instead of a foreach or while when you need to iterate through objects.
@liz, you may want to move the increment after the if (!$child->totalItemCount()) continue; line, so you always have 5 results.
@liz, sorry about that, I was just throwing out code and didn't think about it too much. The second solution wouldn't work because it loops through all of the items before it tests the while expression again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.