2012-06-30 41 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