php - Foreach 的数组不能用作答案键

标签 php arrays

这是我用来计算和显示测验分数的代码...

$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.'%';

关于php - Foreach 的数组不能用作答案键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036441/

相关文章:

php - 1040 php Pdo 异常中的连接过多

php - 在centos上安装composer

php - 在 SQL 中存储标签并检索它

c# - 我想在数组中获取索引,其中包含我在 C# 中的值

arrays - 使用奇怪的分类器查找具有相同 'color' 的 9 个元素

php - 如何知道php文件是从源代码加载的

php - GET 请求错误,Uncaught SyntaxError : Unexpected identifier OPTIONS

javascript - 如何从新的 iframe 重置损坏的 JavaScript 数组对象?

c++ - 通过引用传递数组与传递指针的函数参数绑定(bind)规则

c - 从 Tuple 解析 JSON 数组