如何在foreach循环的单个div中显示3 li?

时间:2018-10-15 06:43:55

标签: php jquery foreach html-lists counter

我有数据收集并通过foreach循环获取详细信息,这很好。

但是我想在单个foreach循环中有3个

  • 例如:

     <ol>
         <div>
             <li></li>
             <li></li>
             <li></li>
         </div>
         <div>
             <li></li>
             <li></li>
             <li></li>
         </div>
         <div>
             <li></li>
             <li></li>
             <li></li>
         </div> 
     </ol>
    

    我正在使用以下代码显示数据:

    <ol class="product-items widget-viewed-grid">
        <?php $iterator = 1; ?>
        <div id="mp-list-items-<?php echo $block->getSliderId(); ?>" class="owl-carousel owl-theme">
            <?php foreach ($items as $_item): ?>
            <?php echo ($iterator++ == 1) ? '<li class="product-item product-slider"">' : '</li><li class="product-item product-slider"">' ?>
            <div class="slider-product-item-info">
                <div class="product details slider-product-item-details">
                    <strong class="product name product-item-name">
                        <a title="<?php echo $block->escapeHtml($_item->getName()) ?>" href="<?php echo $block->getProductUrl($_item) ?>">
                            <?php echo $block->escapeHtml($_item->getName()) ?>
                        </a>
                    </strong>
                </div>
            </div>
            <?php echo ($iterator == count($items) + 1) ? '</li>' : '' ?>
            <?php endforeach ?>
        </div>
    </ol>
    
  • 2 个答案:

    答案 0 :(得分:0)

           echo "<ol>";
               for( $i=0; $i<3; $i++ ) {
               echo "<div>";
                   for($j=0; $j<3; $j++) {
                   echo "<li>";
                       echo "</li>";
                   }
                   echo "</div>";
           }
           echo "</ol>";
    

    答案 1 :(得分:0)

    您必须使用嵌套循环。产品<div>的外循环和产品<li>的内循环。

    例如

    foreach($products as $product){
        echo "<div class='product'>";
        //Now you can call sql query to get items by product id
        foreach($items as $item){
          echo "<li class='list-item'>" . $item->name . "</li>";  //assuming $item has name property
        } //end of inner loop
        echo "<div class='product'>";
    } //end of outer loop