我正在试图弄清楚如何在foreach循环内的特定点放置其他文本,因此我的php的输出将是:
Alabama Alaska Arizona Arkansas 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++;
}
?>
有什么想法吗? THX。
答案 0 :(得分:2)
除了你需要关闭你的foreach循环之外,那个逻辑看起来还不错。
$count = 0;
foreach ($items as $item)
{
if ($count == 3)
{
echo '<td>SomeNewText</td>';
#continue;
}
echo $item;
echo "\n";
$count++;
}
或者,您可以使用for循环。
答案 1 :(得分:0)
如果你的意思是在满足条件时脱离循环,你可以这样做:
<?php
foreach ($items as $item) {
if ($count == 3) {
break;
}
}
?>
答案 2 :(得分:0)
好吧不确定你想要排序的问题是什么,但是你需要关闭foreach循环的代码中有一个错误,这应该会给你你想要的结果。
echo $item;
echo "\n";
$count++;
} <-- here is missing
?>