Php For Loop提供额外的迭代

时间:2018-05-16 18:31:04

标签: php html for-loop foreach

我想在这里找点事。

我有一个反序列化的数组,其中包含来自数据库的多项选择问题到下拉列表中。

我需要这个循环,所以当这个人提交答案时,评分页面需要知道需要多少循环才能计算出正确与错误的答案。

我的问题是,它会在一个额外的时间内通过测试问题进行计数,并在最后给出错误的结果。例如,当只有一个问题时,说“你有2个问题正确”。

这是从数据库打印的数组,测试者在提交答案之前看到了。

<form class="create-test" action="grade.php" method="POST">



 <?php
    $numberOfLoops = 1;
    foreach ($testArray as $testArray['row']) {
        //echo  $testArray['row']['choice1'];

    //}
    //for ($i = 1; $i <= $quantity; $i++){
    ?>
        <label for='test-question'><?php echo $testArray['row']['question']; ?></label>

        <!-- Loop to go through the question array from the database, to be posted to the grading funciton -->
        <select class = 'form-control' name="Question<?php echo $numberOfLoops; ?>">
          <option value="Select an answer" disable selected hidden>Select an answer</option> 
          <option value="<?php echo $testArray['row']['choice1']; ?>"><?php echo $testArray['row']['choice1']; ?></option>
          <option value="<?php echo $testArray['row']['choice2']; ?>"><?php echo $testArray['row']['choice2']; ?></option>
          <option value="<?php echo $testArray['row']['choice3']; ?>"><?php echo $testArray['row']['choice3']; ?></option>
        </select> 

        <input type="hidden" class='form-control' id='actanswer' name="actanswer<?php echo $numberOfLoops; ?>"  value="<?php echo $testArray['row']['answer']; ?>">
        <div class="line"></div>
        <?php
            $numberOfLoops++;
        }

        echo "<input type='hidden' name='numberOfLoops' value='".$numberOfLoops."'>";
    ?>
    <input type='hidden' name='test-id' value="<?echo $testID; ?>">
    <button type="submit" class="btn btn-primary btn-lg" name='submit-answers'>Submit Answers</button>
</form>

这是寻找答案的for循环。

  $correct = 0;
    $incorrect = 0;

    $num = $_POST['numberOfLoops'];

echo $num;

for ($x = 1; $x <= $num; $x++) {
    $response = $_POST['Question'.$x];
    echo $response."<br>";
    $answer = $_POST['actanswer'.$x];
    echo $answer."<br>";
    if($answer == $response){
        $correct++;


    }elseif($response !== $answer){
        $incorrect++;
    }


}

无论有多少问题,它总是会算一个额外的。

所有帮助和反馈都表示赞赏。

编辑:作为更多的信息,有一个回声标记,可以说你x右和y不正确。如果测试是两个问题,它会说。 “你有3个问题,0个错误。”即使只有两个问题。

2 个答案:

答案 0 :(得分:1)

不要这样做

foreach ($testArray as $testArray['row']) {

这在$testArray中创建了一个新的出现,可能解释了你的额外迭代。

而是尝试

foreach ($testArray as $row) {

并修改此行后面的代码以使用$row['choice1']等等

实施例

$sessions = [ 'a','b'];
foreach ( $sessions as $sessions['row']) {
    echo $sessions['row'].PHP_EOL;
}

print_r($sessions);

将输出:

a
b
Array
(
    [0] => a
    [1] => b
    [row] => b
)

答案 1 :(得分:1)

我认为这是你所看到的主要原因:

$numberOfLoops = 1;

然后你为每个问题增加它。所以$numberOfLoops总是比问题的数量多一个。然后在for循环的延续条件中,您有

$x <= $num

因此,如果您有两个问题,例如,$numberOfLoops将为3,并且循环将执行三次。