满足条件后计数计算记录


count to calculate records after conditions are met

我有这个foreach来显示单独的课程。但是,正如您在下面的代码中看到的,我省略了一些记录。此外,通过使用$found,我将消息减少到只有一条消息。

$found = false;
foreach($lessons as $lesson)
{
    if(Auth::LoggedIn())
    {
       if(Auth::$userinfo->rank == 'Student')
       {
           if($lesson->aircraft == 'C172')
           {
                $found = true;
                break;
           }
           if($lesson->theory == '1')
           {
                $found = true;
                break;
           }
       }
     /* Actual foreach data here, a table row displaying a result */
}
if($found)
{
    echo '<div class="msg-yellow"><strong>A selection of lessons could not be displayed, because you have to complete other lessons first.</strong></div><br/>';
}

我想知道如何对另一条消息做相反的解决方案。基本上,我有这个消息,它计算了所有找到的记录。我想让消息消失,如果没有显示记录,再加上我发现每当记录被隐藏时,下面的解决方案仍然会计算它们。

假设数据库中有50条记录,而$if(lesson->aircraft == 'C172'会遗漏6条记录。它应该显示为44,而不是像现在这样显示为50。我想这是因为我拥有的count在foreach之外,在它上面,所以它在条件之前计算所有记录。

<div class="msg-blue"><strong>Your search criteria returned <?php echo count($lessons); ?> lessons available for booking.</strong>

我怎样才能使上面的内容只在满足if条件时显示,并且在没有显示记录时使消息消失?

使用count($lessons)显示计数是不正确的,因为$lessons可能包含您不想显示的记录。相反,您应该创建另一个计数器变量(例如$countLesson);在顶部将其设置为0,并在$found=false时在foreach中增加它。此计数器变量将为您提供正确的计数。

如果没有记录则不显示消息,您可以使用:

if ($countLesson > 0) {
    // display message
}

希望有帮助!

计算隐藏结果的数量,并从总结果中减去它们,得到实际显示结果的数量。要在没有显示结果时隐藏消息,只需检查该差值是否大于0。为了保持表的顺序,必须将表缓存在一个变量中(在本例中为$table),直到显示了搜索结果的数量。

$hidden_count = 0;
$table = "";
foreach($lessons as $key => $lesson)
{
    if(Auth::LoggedIn())
    {
       if(Auth::$userinfo->rank == 'Student')
       {
           if($lesson->aircraft == 'C172')
           {
                $hidden_count += 1;
                break;
           }
           if($lesson->theory == '1')
           {
                $hidden_count += 1;
                break;
           }
       }
     /* Actual foreach data here, a table row displaying a result, not echoed but appended to $table */
}
$count_after = count($lessons) - $hidden_count;
echo '<div class="msg-blue"><strong>Your search criteria returned $count_after flights available.</strong>';
echo $table;
$count_diff = $count_before - $count_after;
if($hidden_count > 0 && $count_after > 0)
{
    echo '<div class="msg-yellow"><strong>$count_diff lessons could not be displayed, because you have to complete other lessons first.</strong></div><br/>';
}