只在foreach中返回一次内容


Echo content inside foreach only once

我试图在foreach中echo一次内容。此时,当用户填写表单时,将为跳过的每条记录显示消息。如果有35条记录被跳过,我将得到35条消息,因为foreach。我希望避免这种情况,并且能够在整个结果页面中只显示一个回声。我该怎么做呢?我想我可能必须在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 &跳出—然后在最后循环遍历错误数组,显示有关错误的更多信息,以便最终用户可以立即纠正它们(当然,这取决于您的表单如何工作)。