2017-05-05 152 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