[英]Echo content inside foreach only once
我試圖回憶一下foreach中的內容。 此時,當用戶填寫表單時,將顯示每個跳過的記錄的消息。 如果跳過35條記錄,由於foreach,我將收到35條消息。 我想避免這種情況,並且只能為整個結果頁面顯示一個回聲。 我怎樣才能做到這一點? 我想我可能不得不在foreach之外做這件事,但我不知道如何把它從foreach中取出來。
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
if($course->aircraft == '2')
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
假設您必須維護該對象的結構,如果$course->aircraft == 1
則可以進行布爾更新,然后相應地進行回顯:
$found = false;
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$found = true;
}
}
}
}
if($found)
{
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
}
在這種情況下,您可以設置一個簡單的標志變量。
$warningEmitted = false;
然后,在發出警告之前的循環中:
if(!$warningEmitted) {
// echo warning here.
$warningEmitted = true;
}
最好的選擇可能是將消息設置為變量,然后在foreach完成后回顯變量。
foreach($allcourses as $course)
{
if(Auth::LoggedIn())
{
if(Auth::$userinfo->rank == 'Student')
{
if($course->aircraft == '1')
{
$message = '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
continue;
}
}
}
}
if(isset($message))
{
echo $message;
}
循環外假設$count=1;
在循環內部,您可以放置一個if語句。
if($count==1) { $count++; echo "Whatever";}
希望這可以幫助。
只需使用最初設置為false的布爾變量,如果得到匹配,則在循環中將其設置為true。
然后你可以在循環結束后檢查布爾值,以決定是否需要顯示消息。
創建其他變量,您將在其中存儲消息是否已顯示的信息。 顯示它時,將var設置為true。
假設我理解正確,我想你一旦發現問題就想用'break'來停止循環。
if (Auth::LoggedIn() && Auth::$userinfo->rank == 'Student') {
foreach ($allcourses as $course) {
if ($course->aircraft == '1') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
if ($course->aircraft == '2') {
echo '<div class="msg-red">Some lessons could not be found, because you may not be entitled to view/book them at this stage of your course.</div><br/>';
break;
}
}
}
上面我還將“if logged in”條件移到了循環之外(所以它只檢查過一次)。
要考慮的事情:
更加用戶友好的方法可能是將每個錯誤添加到一個數組中 - 而不是使用echo和break - 然后在最后循環遍歷該錯誤數組,顯示有關錯誤的更多信息,以便可以一次性更正所有錯誤最終用戶(當然,取決於您的表單的工作方式)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.