1

我有一套答案和学生答案。我想要做的是,对于每个问题,如果个别学生的答案与个别答案匹配,则以绿色显示个别学生的答案,如果个别学生的答案不在答案中,则以红色显示个别学生的答案。

例如:

例如:

Answer: B,C
Student Answer: B,D

上述输出应将学生答案 B 显示为绿色,因为它与答案 B 匹配,但学生答案 D 应显示为红色,因为答案中没有 D。但是使用当前代码,它会将两个学生的答案都显示为红色。

如何解决这个问题?

下面的代码:

        if($questionData['answer'] == $questionData['studentanswer'])
{
    echo '<td width="30%" class="studentanswer green"><strong>'.htmlspecialchars($questionData['studentanswer']).'</strong></td>' . PHP_EOL;
    $check = true;
}
else
{
    echo '<td width="30%" class="studentanswer red"><strong>'.htmlspecialchars($questionData['studentanswer']).'</strong></td>' . PHP_EOL;
    $check = false;
}

更新:

对上述示例执行以下操作:

print $questionData['answer'];
print $questionData['studentanswer'];

我得到这个输出:

B,CB,D
4

2 回答 2

1

$questionData['answer'];是一个内容为 'B,C' 的字符串。因此,您应该只比较字符串的一部分。同理,$questionData['studentanswer']也是一个字符串。您可以分解它们,然后逐个成员比较值。这应该可以解决问题。

$RealAn = explode (',', $questionData['answer']);
$StudedntAn = explode (',', $questionData['studentanswer']);

// This error is from the way $questionData['answer'] is formatted.
// 'D,A,,C' should also work but 'D, A,B,C' won't
if (count($RealAn) != count($StudedntAn))
  echo "There was a problem with your answers.";

// Apparently you only want a row of the table with all the results, outside the loop
echo '<td width="30%" class="studentanswer"><strong>';

// Initialize the checking parameter as not null (so it's safe to use it later)
$check = TRUE;

// Iterate for as many array members as there is
for ($i = 0; $i < count ($StudentAn); $i++)
  {
  // Save what kind this particular member is
  $class = ($RealAn[$i] == $StudentAn[$i]) ? 'green' : 'red';

  // Display each member with the color previously associated to it
  echo '<span class = "' . $class . '">' . htmlspecialchars($StudentAn[$i]) . '</span>';

  if ($i != count($StudentAn)-1)
    echo ', ';

  // If only one of the members is not the same, $check will be false
  if ($class == 'red')
    $check = FALSE;
  }

echo '</strong></td>';
于 2013-03-08T13:24:46.853 回答
0

试试这个

  <head>
  <style>
          .red{color:red;}
          .green{color:green;}
  </style>
  </head>

<?php
  echo GetAns("B D C","B C D F");

function GetAns($ans,$stuAns)
{
    $arr_ans=explode(" ", $ans);
    $arr_stu_ans=explode(" ",$stuAns);
    $str="";
    for($cnt=0;$cnt<count($arr_stu_ans);$cnt++)
    {
        $stu_ans= $arr_stu_ans[$cnt];
        if(in_array($stu_ans,$arr_ans))
            $class="green";
        else
            $class="red";
        $str.="<span class='$class'> $stu_ans </span> ";
    }
    return $str  ;


}

?>
于 2013-03-08T13:18:05.187 回答