检查多个值计数

时间:2017-10-01 20:12:32

标签: php arrays foreach

我需要检查一下是否包含5名学生

来自同一班级的3名学生。

这是我试过的

<?
//this array contains all student id's that are in an exam
$exam = array('s1' => $s1, 's2' => $s2, 's3' => $s3, 's4' => $s4, 's5' => $s5);

$values = implode(", ", $exam);

$sql = "SELECT class FROM students WHERE students.id IN (" . $values . ")";

try{
    $db = new db();
    $db = $db->connect();
    $stmt = $db->query($sql);

    $studs = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $db = null;

    if(!empty($studs)) {

        //check if 3 students from the same class are taking the exam   
        $i = 0; $s = 0;
        foreach($exam as $e )
        {
          if( !in_array( $e, $studs[$i] ) )
          {
            $exist = FALSE;
          }
          else {$s++;}
          $i++;
        }

    if ($s<=3) {
        #do sth
    }
    else {
        echo "more than 3 students";
    }

    } else {  
        echo "error";
    }
} catch(PDOException $e) {}
?>

问题 我不确定的是如何计算这3名学生在这个考试阵列中具有相同的班级ID。

我知道在我的foreach中有一些东西需要修复,只是尝试没有成功。

2 个答案:

答案 0 :(得分:0)

您可以要求您的数据库返回所有来自您的ID列表中的3个或更多学生的班级,方法是使用HAVING子句对您的结果进行聚合和分组:

SELECT class,COUNT(id)as num_students_in_class FROM students WHERE id IN(1,2,3,4)GROUP BY class HAVING COUNT(id)&gt; = 3

更多信息: How to use group by in SQL Server query? What's the difference between HAVING and WHERE?

答案 1 :(得分:0)

如果您不想按照https://stackoverflow.com/a/46517195/100809中的建议进行查询,则需要保留类的关联数组以及您看到它的次数:

$seenClasses = array_count_values($studs);

foreach($seenClasses as $class => $numStudents) {
    if ($numStudents > 4)
        echo “class $class has $numStudents”;
}