2011-02-11 199 views
0

我試圖找出如何放置其他文本在foreach循環內的特定點,所以我的PHP的輸出將是額外的文字:中斷foreach循環添加

阿拉巴馬阿拉斯加亞利桑那阿肯色SomeNewText 加利福尼亞州科羅拉多州康涅狄格州等等等等

繼續;並打破;在這種情況下似乎不起作用。我不要想停止/退出foreach循環。

<?php 

$items = array("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Dist of Columbia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"); 


$count = 0; 

foreach ($items as $item) 
{ 

if ($count == 3) 
{ 
echo 'SomeNewText'; 
} 

echo $item; 
echo "\n"; 

$count++; 

} 

?> 

任何想法?謝謝。

+0

您的標題和您的文字看起來像單獨的問題。計數達到3時是否要退出foreach循環? – arnorhs 2011-02-11 00:12:18

+0

你絕對不希望**繼續**。 Aaand是的,你需要關閉你的foreach循環。除此之外,代碼應該完成這項工作。 – bassneck 2011-02-11 00:13:45

回答

0

如果你的意思是從此告別當條件滿足時,循環的時候,你可以這樣做:

<?php 
foreach ($items as $item) { 
    if ($count == 3) { 
    break; 
    } 
} 
?> 
2

這個邏輯看起來不錯,但你需要關閉你的foreach循環。

$count = 0; 
foreach ($items as $item) 
{ 

if ($count == 3) 
{ 
echo '<td>SomeNewText</td>'; 
#continue; 
} 

echo $item; 
echo "\n"; 

$count++; 
} 

或者,您可以使用for循環。

0

不知道你想要排序的問題是什麼,但是在你的代碼中有一個錯誤,你需要關閉foreach循環,這應該給你你想要的結果。

echo $item; 
echo "\n"; 

$count++; 

} <-- here is missing 

?>