I have a list of 6 products that i want to split in 2 lists of 3 products next to each other. The list are made within a foreach loop, the first list stops after the count == 2, so 3 items wil be displayed. The second list should start with the fourth item. How can i achieve this?
This is wat makes the first list of 3 items:
$_categoryId = explode(' ', $category['id']);
$count = 0;
$_productCollection = Mage::getModel('catalog/category')->load($_categoryId)
<?php foreach ($_productCollection as $_product): ?>
<a class="product-name" href="<?php echo $_product->getProductUrl() ?>">
<?php echo $this->htmlEscape($_product->getName()) ?>
if($count == 2) break; // Stop after 3 items
<?php endforeach ?>
For simplicity you could repeat the
foreach statement but doing the opposite and
continue on the first three items.
<?php foreach ($_productCollection as $_product): ?> <?php $count++; // Note that first iteration is $count = 1 not 0 here. if($count <= 3) continue; // Skip the iteration unless 4th or above. ?> <li class="category-row-list-item"> <a class="product-name" href="<?php echo $_product->getProductUrl() ?>"> <?php echo $this->htmlEscape($_product->getName()) ?> </a> </li> <?php endforeach ?>
continue is used in loops to skip the current iteration without exiting the loop, in this case it makes PHP go directly back to the first line of the
foreach-statement, thus increasing counter to 4 (since 4th, 5th and 6th is what we're after) before passing the
Commentary on the approach
I kept it coherent with your existing solution but a more clean way in this case would probably be to use the built in Collection Pagination.
If you use
->setPageSize(3) you can simply iterate the collection to get the first three products and then use
->setCurPage(2) to get the second page of three items.
I'm linking this blog post on the topic here just to give you an example of how it's used but since I don't know your comfort level in working with collections I retain my first answer based on your existing code.