2017-05-05 154 views
0

我有2個循環內環&外環。在每次外循環迭代後運行內環

當外循環達到第三次迭代時,內循環應該運行。我喜歡這樣。

<?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 
     } 
?> 

,結果都是這樣

enter image description here

問題:

的問題是,內環示出了第三次迭代後的所有結果。但是我只想顯示內部循環的一個結果,然後內部循環的第二個結果應該在外部循環的下一個3次迭代之後顯示。

我該如何解決這個問題?

+1

使用簡單'$這個 - > domain_ads [0]'insted的的foreach? –

回答

1

簡單的解決方案:

<?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++; 
    } 
} 
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 

希望這將有助於 Demo