【问题标题】:PHP Quiz Radio and Checkbox CalculationPHP 测验单选和复选框计算
【发布时间】:2020-08-15 19:56:11
【问题描述】:

我正在使用 PHP 设计一个简单的测验,并想知道在继续之前我是否以正确的方式接近它。

测验将有大约 25 个问题,包括单选按钮和复选框。这个想法是计算总数并在提交测验时将其显示给用户。

到目前为止,我只有四个问题。问题 1 - 3 是单选按钮,最多选择一个。问题 4 是一个复选框,最多允许两个选择,每个正确的选择值 0.5

这是我的 html 代码的 sn-p(问题和答案文本已删除)。

HTML

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

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

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

// q4 answer is value 1 or 3. 0.5 points each
<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 代码有效,它是正确的方法还是有更有效的方法?特别是复选框问题4。

PHP

$total = array();

$total = '0';

$q1 = $_POST['form']['1-1'];
$q2 = $_POST['form']['1-2'];
$q3 = $_POST['form']['1-3'];
$q4 = $_POST['form']['1-4'];

// answer with value 2 is correct
if ($q1 == '2' ) {
    $total++;
};
// answer with value 1 is correct
if ($q2 == '1' ) {
    $total++;
};
// answer with value 2 is correct
if ($q3 == '2' ) {
    $total++;
};
// answer with value 1 is correct
if ($q4[0] == '1' ) {
    $total = $total + 0.5;
};
// answer with value 3 is correct
if ($q4[1] == '3' ) {
    $total = $total + 0.5;
};

// send $total to database here

我不想使用 JS / Jquery,我想使用 PHP 方法。

【问题讨论】:

    标签: php html loops if-statement post


    【解决方案1】:

    这是一个更动态的版本,也适合从数据库加载。

    solutions数组有问题和答案的列表,如果是多选题,那么答案就是正确值的数组。

    循环遍历解决方案并将答案与预期的解决方案进行比较。如果答案不存在,?? null 会设置它,但它不应与结果匹配。

    $solutions = ['1-1' => 2, '1-2' => 1, '1-3' => 2, '1-4' => [1,3]];
    
    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);
        }
    }
    

    【讨论】:

    • 我在答案的底部添加了一些替代代码。通常最好添加一个新问题,尤其是这个问题已经超过一个月了。
    • 谢谢我刚刚在您回答这个问题时发布了一个问题!看到这里stackoverflow.com/questions/62170058/…再次感谢更新
    • 这很有帮助,因为最初回答的人可能不在身边,可以给你一个更快(有时)更好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    相关资源
    最近更新 更多