在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
}
}
我有通过 我的帖子和广告块没有问题。 这些帖子来自一个阵列和我手动插入的广告块。 p>
我看到的打嗝是如何将这些广告投入 我每页有3个广告块和12个帖子。 当页面加载时,应该总共有15个块,而我得到9.这些广告也不是静态的 - 我让它们进入总共15个块中的任何位置。 p>
foreach code>循环显示的帖子。 在此我想投入一些广告块。 p>
foreach code> 环。 我希望它添加它们但不会中断帖子本身,这就是我所经历的。 p>
$ i = 0;
foreach($ posts AS $ post){
$ i ++;
if($ adblock == $ i){
//插入广告块
}
否则if($ adblock == $ i){
//插入广告块
}
否则if( $ adblock == $ i){
//插入广告块
}
其他{
//插入帖子块
}
}
code> pre>
div >
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.