阅读数组和显示中的问题和答案

时间:2013-04-25 09:55:15

标签: arrays comparison

比较数组元素,如果数组相同或不相等,则加1或0。但他们并没有加起来,我在哪里做错了?因为数组似乎没有比较。

<html>
<head>
<title>Chosen answers</title>
</head>
<body>
<pre>
<?php

//Posting of the chosen answers

$answers = $_POST['selected_answers'];
echo '<b><u>THE ANSWERS YOU HAVE CHOSEN ARE:</u></b><br /><br />';
print_r($answers);

//Opening of the answers file, reading and printing it

$openFile = fopen("answers.txt", "r") or exit ("unable to open the answers file");
$fileContents = fread($openFile, filesize("answers.txt"));
fclose($openFile);
$delimiter = "  ";
$myArray = explode($delimiter, $fileContents);

$score = $score1 = $score2 = $score3 = $score4 = $score5 = $score6 = $score7 = $score8 = 0;

//Computation of marks scored for the answered questions

if ($answers[0] == $myArray[0])
{
$score = 1;
}
elseif ($answers[0] !=$myArray[0])
{
$score = 0;
}echo '<br />';

if ($answers[1] == $myArray[1])
{
$score1 = 1;
}
elseif ($answers[1] !=$myArray[1])
{
$score1 = 0;
}echo '<br />';

if ($answers[2] == $myArray[2])
{
$score2 = 1;
}
elseif ($answers[2] !=$myArray[2])
{
$score2 = 0;
}echo '<br />';

if ($answers[3] == $myArray[3])
{
$score3 = 1;
}
elseif ($answers[3] !=$myArray[3])
{
$score3 = 0;
}echo '<br />';
if ($answers[4] == $myArray[4])
{
$score4 = 1;
}
elseif ($answers[4] !=$myArray[4])
{
$score4 = 0;
}echo '<br />';

if ($answers[5] == $myArray[5])
{
$score5 = 1;
}
elseif ($answers[5] !=$myArray[5])
{
$score5 = 0;
}echo '<br />';

if ($answers[6] == $myArray[6])
{
$score6 = 1;
}
elseif ($answers[6] !=$myArray[6])
{
$score6 = 0;
}echo '<br />';

if ($answers[7] == $myArray[7])
{
$score7 = 1;
}
elseif ($answers[7] !=$myArray[7])
{
$score7 = 0;
}echo '<br />';

if ($answers[8] == $myArray[8])
{
$score8 = 1;
}
elseif ($answers[8] !=$myArray[8])
{
$score8 = 0;
}

$Total = $score + $score1 + $score2 + $score3 + $score4 + $score5 + $score6 + $score7 +   $score8 ;

echo "<b><u>$Total</u></b>";
?>
</pre>
</body>
</html>

我如何能够比较两个阵列并计算总分数。第一个数组$ answers来自提交的表单。第二个是从另一个名为answers.txt

的文本文件中读取的

1 个答案:

答案 0 :(得分:0)

您的代码太冗余,您应该对其进行优化。试试吧

<?php 

$total=0;
if ($answers[1]=="Data coupling")
{
$total++;
}
else
{
print_r($answers[1]);
}

//third question
if ($answers[2]=="Unit testing")
{
$total++;
}
else
{
print_r($answers[2]);
}

//fourth question

if ($answers[3]=="Mutation testing")
{
$total++;
}
else
{
print_r($answers[3]);
}
//fifth question

if ($answers[4]=="white box testing")
{
$total++;
}
else
{
print_r($answers[4]);
}

//sixth question

if ($answers[5]=="Ad hoc")
{
$total++;
}
else
{
print_r($answers[5]);
}

//seventh question
if ($answers[6]=="information domain values")
{
$total++;
}
else
{
print_r($answers[6]);
}


//eigth question

if ($answers[7]=="Functional and behavioral")
{
$total++;
}
else
{
print_r($answers[7]);
}

//nineth question

if ($answers[8]=="Efficiency")
{
$total++;
}
else
{
print_r($answers[8]);
}

//code to generate the total score 

    echo $total;
?>