【问题标题】:PHP Quiz Calculation of Array Answers数组答案的PHP测验计算
【发布时间】:2020-09-21 23:41:44
【问题描述】:

我有一个使用 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 and 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);
    }
}

我怎样才能只为完全正确的答案打一分?

【问题讨论】:

    标签: php html arrays


    【解决方案1】:

    如果您只想计算完全正确的答案,那么您可以将预期答案的数量与匹配的数量进行比较,因此将第一个 if 部分更改为...

    if ( is_array($solution) ){
        $correct = array_intersect($solution, $userAnswer);
        $total += (count($solution) == count($correct));
    }
    

    【讨论】:

    • $marksPerAnswer 是任何答案的小数部分,因此有 2 个答案 $marksPerAnswer 将是 0.5。如果您想给每个答案打多个分数,那么您可能需要扩展 $solutions 数组以包含另一个字段(以及处理它的额外代码)。
    • * 5放在括号外——count($correct)) * 5;
    • 当你说仍然不行时,它应该以 0 或 5 分结束(只有当所有都正确时才 5 分),这是你想要的吗?
    • OK - 在循环之后将 $total 乘以 5 是否有同样的效果?
    • 我已经创建了另一个类似的问题,如果您有时间提出答案,那就太好了,谢谢! stackoverflow.com/questions/62431857/…
    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2014-06-02
    相关资源
    最近更新 更多