表格中的Foreach ...限制为7然后创建新行

时间:2014-02-22 15:00:51

标签: php magento foreach

我有这个代码打印出最畅销产品列表的输出。问题是它在没有断裂的情况下水平跨越并且在7种产品之后从屏幕的侧面脱离。

我想做的事情,并且因为我的尝试没有结果而完全受阻,就是让第8到第14个参赛作品开始新的一行。我如何修改代码才能完成此任务?

<?php $products = $this->getCollection(); ?>
<?php if ($products && $products->count() > 0) { ?>

<div class="block block-list block-viewed">
    <div class="block-title">
        <strong><span><?php echo $this->__($this->getHeader()) ?></span></strong>
    </div>
    <div class="block-content">

    <table class="amsorting-table">
        <tr>
        <?php foreach ($products as $p) { ?>
            <td style="padding: 15px 15px 0px 15px;">
                <a href="<?php echo $p->getProductUrl() ?>" title="<?php echo $this->htmlEscape($p->getName()) ?>" class="product-image"><img 
src="<?php echo $this->helper('catalog/image')->init($p, 'small_image')->resize(125) ?>" width="125" height="125" alt="<?php echo 
$this->htmlEscape($p->getName()) ?>" /></a>
                <h3 class="product-name"><a href="<?php echo $p->getProductUrl() ?>" title="<?php echo $this->htmlEscape($p->getName()) 
?>"><?php echo $this->htmlEscape($p->getName()) ?></a></h3>
                <?php echo $this->getPriceHtml($p, true) ?>

            </td>
        <?php } ?>
        </tr>
        <tr>
            <?php foreach ($products as $p) { ?>
               <td style="padding: 0px 15px 15px;">
                <?php if($p->isSaleable()): ?>
                        <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart"
onclick="setLocation('<?php echo $this->getAddToCartUrl($p) ?>')"><span><span><?php echo $this->__('Add to Cart')
?></span></span></button>
                    <?php else: ?>
                        <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                    <?php endif; ?>

            <?php } ?>
              </td>
        </tr>
    </table>

    </div>
</div>

<?php } ?>

1 个答案:

答案 0 :(得分:0)

根据当前产品索引是否可被7整除,有条件地执行<tr>标记

<table class="amsorting-table">
   <?php 
   foreach ($products as $i => $p) { 

     if ($i % 7 == 0) { // start a new row on product 0, 7, 14, etc

        if ($i > 0) { // if this is not the 1st product, close the previous row
           ?></tr><?php
        }

        ?><tr><?php
     }

     ... your code the display the table cell for the current product

   }

   // after the loop, we need to close the last row
   ?></tr><?php
   ...