我有一套答案和学生答案。我想要做的是,对于每个问题,如果个别学生的答案与个别答案匹配,则以绿色显示单个学生答案,如果答案中没有个别学生答案,则显示该个别学生的答案为红色。
例如:
例如:
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
答案 0 :(得分:1)
$questionData['answer'];
是一个包含内容&#39; B,C&#39;的字符串。因此,您应该只比较字符串的一部分。同样,$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>';
答案 1 :(得分: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 ;
}
?>