数组答案的PHP测验计算

我有一个使用 html 单选按钮设计的测验,计算由一些 PHP 处理。


请参阅下面的基本 html 布局(为了便于阅读,删除了一些元素);


// q1 answer is value 2

<input type="radio" name="form[1-1]" value="1">

<input type="radio" name="form[1-1]" value="2">


// q2 answer is value 1

<input type="radio" name="form[1-2]" value="1">

<input type="radio" name="form[1-2]" value="2">


// q1 answer is value 2

<input type="radio" name="form[1-3]" value="1">

<input type="radio" name="form[1-3]" value="2">


// q4 answer is value 1 AND 2 AND 4

<input type="checkbox" name="form[1-4][]" value="1">

<input type="checkbox" name="form[1-4][]" value="2">

<input type="checkbox" name="form[1-4][]" value="3">

<input type="checkbox" name="form[1-4][]" value="4">

我目前使用的 PHP 代码(多亏了PHP Quiz Radio 和 Checkbox Calculation),但是它在具有多个答案的问题上拆分了要点。


$solutions = ['1-1' => 2, '1-2' => 1, '1-3' => 2, '1-4' => [1,2,4]];


foreach ( $solutions as $question => $solution ) {

    $userAnswer = $_POST['form'][$question] ?? null;

    if ( is_array($solution) ){

        $marksPerAnswer = 1/count($solution);

        $correct = array_intersect($solution, $userAnswer);

        $total += $marksPerAnswer * count($correct);

    }

    else    {

        $total += ($userAnswer == $solution);

    }

}

如何只为完全正确的答案分配一分?


慕森卡
浏览 72回答 1
1回答

四季花海

如果您只想计算完全正确的答案,那么您可以将预期答案的数量与匹配的数量进行比较,因此将第一个 if 部分更改为...if ( is_array($solution) ){&nbsp; &nbsp; $correct = array_intersect($solution, $userAnswer);&nbsp; &nbsp; $total += (count($solution) == count($correct));}
打开App,查看更多内容
随时随地看视频慕课网APP