这是我用来计算和显示测验分数的代码…
$answer1 = $_POST['q1'];
$answer2 = $_POST['q2'];
$answer3 = $_POST['q3'];
$answer4 = $_POST['q4'];
$answer5 = $_POST['q5'];
$answer6 = $_POST['q6'];
$answer7 = $_POST['q7'];
$answer8 = $_POST['q8'];
$answer9 = $_POST['q9'];
$answer10 = $_POST['q10'];
$totalCorrect = 0;
if ($answer1 == "A") { $totalCorrect++; }
if ($answer2 == "Jupiter") { $totalCorrect++; }
if ($answer3 == "C") { $totalCorrect++; }
if ($answer4 == "D") { $totalCorrect++; }
if ($answer5 == "A") { $totalCorrect++; }
if ($answer6 == "C") { $totalCorrect++; }
if ($answer7 == "C") { $totalCorrect++; }
if ($answer8 == "C") { $totalCorrect++; }
if ($answer9 == "B") { $totalCorrect++; }
if ($answer10) { $totalCorrect++; }
它有效,但是有点业余.我最终将进行许多测验,所以我想开始尽可能地简化工作.
这个数组看起来很酷-但不起作用.如果我正确回答所有10个问题,它将显示$totalCorrect值为0(由第一行代码指示).如果我将这一行注释掉-// $totalCorrect = 0; -然后它什么也不显示.
$totalCorrect = 0;
$answers = [1 => 'A', 2 => 'Jupiter', 3 => 'C', 4 => 'D', 5 => 'A', 6 => 'C', 7 => 'C', 8 => 'B', 9 => 'B', 10 => 'AA', 11 => 'A'];
foreach ($answers as $num => $answer)
{
$key = 'answer-'.$num;
if (isset($_POST[$key]) && $_POST[$key] === $answer)
{
$totalCorrect++;
}
}
谁能看到我做错了吗?
解决方法:
$key = 'answer-'.$num;
改成
$key = 'q'.$num;
为了更容易理解,也可以尝试一下
$totalCorrect = 0;
$answers = [1 => 'A', 2 => 'Jupiter', 3 => 'C', 4 => 'D', 5 => 'A', 6 => 'C', 7 => 'C', 8 => 'B', 9 => 'B', 10 => 'AA', 11 => 'A'];
foreach ($answers as $num => $answer)
{
$question = 'q'.$num;
if (isset($_POST[$question]) && $_POST[$question] === $answer)
{
$totalCorrect++;
}
}
$pct = round( (($totalCorrect/count($answers)) * 100), 0);
echo $totalCorrect.' correct for '.$pct.'%';
标签:arrays,php
来源: https://codeday.me/bug/20191120/2046968.html