简体   繁体   中英

Run Inner Loop after each 3rd iteration of outer loop

I have 2 loops Inner Loop & Outer Loop.

When Outer loops reaches its third iteration, then inner loop should run. and i do like this.

 <?php 
       foreach($this->posts as $post){ 
 ?>
           <div id="post">
           </div>
          <?php  
                 foreach($this->domain_ads as $ads) { 
                      if($i%3==0){ 
           ?>
                           <div id="ads">
                           </div>
          <?php       }
                 } ?>
 <?php 
      }
 ?>

And the Results are like this

在此处输入图片说明

Problem:

The problem is that inner loop shows all results after 3rd iteration. But i want to show only one result of inner loop, and then second result of inner loop should show after next 3 iterations of outer loop.

How can i solve this problem ?

Simple solution:

<?php
$i = 0;
// counter for ads
$ad_counter = 0;
foreach($this->posts as $post) {?>
<div id="post"></div>
<?php
    $i++;
    // check if it is time to show ad 
    // and if you have ad with `$ad_counter`
    if ($i % 3 == 0 && isset($this->domain_ads[$ad_counter])) {?>
        <div id="ads"><?php echo $this->domain_ads[$ad_counter]['name'];?>></div>
<?php   // increase `$ad_counter` so as to move to next ad
        $ad_counter++;
    }
}
$i = 1;
for($a = 0; $a<=10; $a++){ //your first foreach loop
    echo "abc<br />"; //you div
    if($i%3==0){ //check condition
        for($b=0; $b<2;$b++){ //your inner foreach loop
            echo "xyz<br />"; //inner loop content
        } //end inner loop
    } //end if condition
    $i++;
} //end outer foreach

hope this will help Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM