PHP测验数组答案的计算 [英] PHP Quiz Calculation of Array Answers

查看:47
本文介绍了PHP测验数组答案的计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a quiz designed using html radio buttons and the calculation is handled by some PHP.

请参见以下基本html布局(已删除一些元素以便于阅读);

See below for the basic html layout (some elements removed for ease of reading);

// 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测验单选和复选框计算),但是它在具有多个答案的问题上分了分。

The PHP code I have currently works (thanks to PHP Quiz Radio and Checkbox Calculation), however it splits points on questions with multiple answers.

$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);
    }
}

我该如何为完全正确的答案分配一个点?

How can I assign one point for fully correct answers only?

推荐答案

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

If you want to only count fully correct answers, then you can compare the number of expected answers against the number that match, so change the first if part to...

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

这篇关于PHP测验数组答案的计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆