2012-06-30 38 views
2

应用了什么wrapping objects using math operator后,我只是将它结束了。但不是。到目前为止。一个循环(while/foreach)带有“偏移”包装和

<?php 
$faces= array(
    1 => '<div class="block">happy</div>', 
    2 => '<div class="block">sad</div>', 
    (sic) 
    21 => '<div class="block">angry</div>' 
); 

$i = 1; 
foreach ($faces as $face) { 
    echo $face; 
    if ($i == 3) echo '<div class="block">This is and ad</div>'; 
    if ($i % 3 == 0) { 
    echo "<br />"; // or some other wrapping thing 
    } 
    $i++; 
} 

?> 

在代码中,我必须在第二个代码之后放置广告,然后成为第三个对象。然后将这三个全部包装在一个<div class="row">(之后由于设计原因而不能解决)。我想我会回去应用一个开关,但是如果有人在开关可以正确包装的阵列中放置更多的元素,最后剩下的两个元素将被公开包装。

我可以在第三个位置添加“广告”数组吗?这会让事情变得更简单,只让我猜测如何包装第一,第三,第四和第六,等等。

+4

'如果($ i = 3)'是错误的,并需要'如果($ I == 3)'。 – nickb

回答

1

首先,插入广告:

array_splice($faces, 2, 0, array('<div class="block">this is an ad</div>')); 

然后,应用包装:

foreach (array_chunk($faces, 3) as $chunk) { 
    foreach ($chunk as $face) { 
     echo $face; 
    } 
    echo '<br />'; 
} 
+0

我想你的意思是array_splice($ faces,2 ...)而不是3。如何进入第三个位置,你的位置将进入第四位。 – drewish

+0

它也看起来像你可以删除添加包装数组。 – drewish

+0

@drewish感谢您的评论,我已经应用了位置改变,但是我觉得离开显式数组更好。 –

1

你可以只拆分阵列中的两个,插入您的广告,然后追加休息:

// Figure out what your ad looks like: 
$yourAd = '<div class="block">This is and ad</div>'; 

// Get the first two: 
$before = array_slice($faces, 0, 2); 
// Get everything else: 
$after = array_slice($faces, 2); 
// Combine them with the ad. Note that we're casting the ad string to an array. 
$withAds = array_merge($before, (array)$yourAd, $after); 

我想用比较运算,而不是分配将有助于让你的包裹想出nickb的音符。

+0

这就是它。唷!,这两个帖子都会做这个工作。 – DarkGhostHunter

+0

你的意思是'array_splice()'? :) –

+0

我曾看过array_splice的文档,他们没有清楚地讨论0长度会发生什么。看到它这样工作很有趣。 – drewish