0

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

enter image description here

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 ?

1
  • 1
    Use simple $this->domain_ads[0] insted of foreach? Commented May 5, 2017 at 15:30

2 Answers 2

1

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

Comments

0
$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

Comments

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.