-1

比较数组元素,如果数组相同或不同,则加 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 的文本文件中读取的

4

1 回答 1

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;
?>
于 2013-04-25T10:02:11.287 回答