我正在开展一个大学项目,其中我正在进行在线 MCQ 考试测试。我创建了一个 json 文件来存储问题的数据。我使用 foreach 循环在 php 文件中打印问题。我被困在一个地方,我有一个选定单选按钮的 POST 数组,而在另一个页面上有一个 JSON 文件中的正确答案数组。我想比较两个数组来计算正确答案和错误答案的数量。我的代码唯一的错误是有人没有选择任何有问题的选项。那么我的 POST 数组将无法完美地进行比较。第二个是 Post 数组的格式为
Array ( [question1] => op3 [question2] => op2 [question3] => op3 [question4] => op1 [question5] => op3 [submit] => SUBMIT )
而 JSON 数组是这样的
[0] => op1 [1] => op1 [2] => op1 [3] => op1 [4] => op1 )
我如何比较这两个不同索引的数组,以便我可以计算错误和正确的数量..
这是我的总代码 HTML
form id="gi" method="post" action="checkAnswer.php">
<?php
foreach ($json_data as $key => $value) {
echo
"<p><span class='que'> Question</span>  ". $value['number']."  ". "<br><hr class='line'>". $value['question']."<br><br>".
"<pre>"."<input type='radio' name='question" . $value['number']."' value='op1'>" ." " , $value['op1']."</pre>".
"<pre>"."<input type='radio' name='question" . $value['number']."' value='op2'>" ." " , $value['op2']."</pre>".
"<pre>"."<input type='radio' name='question" . $value['number']."' value='op3'>"." " , $value['op3']."</pre>".
"<pre>"."<input type='radio' name='question" . $value['number']."' value='op4'>"." " , $value['op4']."</pre>".
"</p>";
}
?>
<input class="submitBtn" type="submit" name="submit" value="SUBMIT">
<!-- <button onclick="handleClick()">click</button> -->
</form>
这是 json
[
{
"number": 1,
"question": "Eighteen thousandths, written as a decimal, is:",
"op1" : 20,
"op2" : 30,
"op3" : 59,
"op4" : 54,
"correct_answer": "op1"
},
{
"number": 2,
"question": "Eighteen thousandths, written as a decimal, is:",
"op1" : 20,
"op2" : 30,
"op3" : 59,
"op4" : 54,
"correct_answer": "op1"
},
{
"number": 3,
"question": "Eighteen thousandths, written as a decimal, is:",
"op1" : 20,
"op2" : 30,
"op3" : 59,
"op4" : 54,
"correct_answer": "op1"
}
]
这是我执行常见操作的代码
<?php
$contentOfJsonFile = file_get_contents("example_10.json");
$JsonData = json_decode($contentOfJsonFile, true);
$correctAnswerArray = [];
// Defination of all global variables
$wrongCount = 1;
// this will push the correct answer from the json to an array
foreach ($JsonData as $key => $value) {
array_push($correctAnswerArray, $value['correct_answer']);
}
print_r($correctAnswerArray);
// this is printing the post array
$userAnswerArray = $_POST;
print_r($userAnswerArray);
//comparing two arrays
for ($i = 0; $i <= count($userAnswerArray); $i++) {
for ($j = 0; $j < count($correctAnswerArray); $j++) {
if ($correctAnswerArray[$j] != $userAnswerArray[$i])
$wrongCount++;
else
$correctCount++;
}
}
echo $correctCount;
echo $wrongCount;
?>```
最佳答案
foreach ($userAwnserArray as $key => $answer) {
# get question number
$questionNumber = substr($key, -1);
# get answer of the question in the foreach loop and compare to the correct answer
if ($correctAnswerArray[$questionNumber] === $answer) {
# increment correct
$correctCount++;
} else {
# increment wrong
$wrongCount++;
}
}
我还没有测试过它,但我认为它会插入你走向正确的方向
关于javascript - Post 数组与 Json 数组的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58818659/