2

我想使用 PHP 对测验进行评分。我有一个测验,提交后会提供一系列答案。它们都是真/假,所以数组类似于

array([0] => T, [1] => F, [2] => F)

然后我有一个答案键,比如

array([0] => T, [1] => F, [2] => T)

我需要检查每个答案,这样我不仅可以计算正确百分比,而且当且仅当遗漏问题的数量少于 20% 时,才能显示遗漏问题的正确答案。

所以我的问题是,我应该做某种 foreach 循环来遍历每个循环,还是使用某种数组比较函数会更整洁,如果是这样,哪个?

4

3 回答 3

3

使用foreach()

$answer   = array(true, true, false, true, false);
$expected = array(true, true, true,  true, false);
$error    = array();

foreach ($answer as $k => $v) {
  if ($v !== $expected[$k])
    $error[$k] = $v;
}

// Display the correct answer if number of mistakes is <= 20%
if (floatval(count($error) / count($expected)) <= .2) {
  $correct = array_intersect_key($expected, $error);
}
于 2012-06-01T17:22:42.753 回答
0

使用 foreach 循环,您将拥有更多控制权。您可以通过将数组中的相等值除以总问题数来确定正确的百分比。

于 2012-06-01T14:19:49.547 回答
0

以分级阵列为起点。由于它应该包含所有键(对于所有问题),您可以使用它们来检测提交数组中缺少的键找到所有答案。如果您要手动计算报告,下面是一个示例:

$submission = array(1 => true, 3 => false, 4 => true, 100 => true);
$grading = array(0 => true, 1 => true, 2 => true, 3 => true, 4 => true);


//gather data
$answered = array();
$missing = array();
$correct = array();
$wrong = array();
foreach ($grading as $key => $answer) {
    if(array_key_exists($key, $submission)) {
        array_push($answered, $key);
        if ($submission[$key] === $answer)
            array_push($correct, $key);
        else
            array_push($wrong, $key);
    }
    else
        array_push($missing, $key);
}


//print report
echo "correct\n";
print_r($correct);
echo "\n\n";

echo "wrong\n";
print_r($wrong);
echo "\n\n";

echo "missing\n";
print_r($missing);
echo "\n\n";

echo "% answered\n";
echo 100*(count($answered)/count($grading));
echo "\n\n";

echo "% correct (of all questions)\n";
echo 100*(count($correct)/count($grading));
echo "\n\n";

echo "% correct (of all answered)\n";
echo 100*(count($correct)/count($answered));
echo "\n\n";

echo "% wrong (of all questions)\n";
echo 100*(count($wrong)/count($grading));
echo "\n\n";

echo "% wrong (of all answered)\n";
echo 100*(count($wrong)/count($answered));
于 2012-06-01T14:40:59.333 回答