dplm47571 2016-11-30 22:14
浏览 200
已采纳

在foreach循环中插入随机块

I have posts that I am displaying through a foreach loop. Within this I would like to throw in some advertising blocks.



I have posts and advertising blocks working with no issues. The posts are coming from an array and the advertising blocks I am manually inserted.

The hiccup I am seeing is how I am throwing in these ads into the foreach loop. I want it to add them but not interrupt the posts themselves and that is what I am experiencing.



I have 3 advertising blocks and 12 posts per page. When the page loads there should be a total of 15 blocks and instead I am getting 9. Those ads also not static - I have them coming in to be placed anywhere within those 15 blocks in total.


Here is quick run down of the script I am using (a readers digest version).



$i = 0;
foreach ($posts AS $post) {

   $i++;

   if ($adblock == $i) {
        //insert advertisement block
   }
   else if ($adblock == $i) {
        //insert advertisement block
   }
   else if ($adblock == $i) {
        //insert advertisement block
   }
   else {
        //insert post block
   }

}
  • 写回答

1条回答 默认 最新

  • dongxi1965 2016-11-30 22:22
    关注

    Without too much complexity, if the number of posts/adv per page is static, you can use a simple math to place your adv like this:

    $i=0;
    foreach($posts as $post){
      $i++; 
    
      if($i%3==0) { /* insert additional adv block */ }
    
      /* insert post block at anytime*/
    }
    

    you can change the ($i%3==0) to any other number; with 3 you will get an adv every 3 posts. need more adv, make it ($i%2==0), need less, make it ($i%4==0), etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?