Foreach不作为答案密钥的数组

时间:2015-01-20 01:39:55

标签: 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++;
 }
}

谁能看到我做错了什么?

3 个答案:

答案 0 :(得分:1)

q[n]数组中有answer-[n]$_POST个密钥。只需使用以下内容:

foreach ($answers as $num => $answer)
    if (isset($_POST['q' . $num]) && $_POST['q' . $num] === $answer)
        $totalCorrect++;

答案 1 :(得分:1)

您为了您的目的而错误分配$key

在您的第一个(工作示例)中,密钥为'q1''q2'等。 在第二个示例中,您的密钥为'answer-1''answer-2'等。

$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 = 'q' . $num;  //fixed code here
  if (isset($_POST[$key]) && $_POST[$key] === $answer) {
    $totalCorrect++;
  }
}

答案 2 :(得分:1)

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