在PHP中比较数组中值的最有效方法

时间:2012-06-01 14:16:45

标签: php arrays comparison

我想用PHP来评分测验。我有一个测验,在提交后,会提供一系列答案。它们都是真/假,所以数组就像

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

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

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

我需要仔细检查每个答案,这样我不仅可以计算出正确的百分比,而且还可以显示错过的问题的正确答案,当且仅当错过的问题数量少于20%时。

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

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

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

答案 2 :(得分: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));