猿问

如何计算php中具有不同值的文件的匹配项数量

对于多项选择考试,我将数据存储在文件中。.txt


我有8个文件,其中存储了2个或更多数字。txt 文件的名称是.txt1.txt, 2.txt, 3.txt ...


每个 txt 文件中的第一个数字始终是正确的答案。我想将第一个数字与该txt文件的最后一个数字进行比较。


foreach($all_files as $file) {

    $each_file = file_get_contents($file);

    $choosen_answer = substr($each_file, -1); // last number is the number user has choosen

    $correct_answer = substr($each_file, 0,1); // first number is the correct answer


    // output the answers

    echo '<span class="choosen_answer">'.$choosen_answer.'</span>'; 

    echo '<span class="correct_answer">'.$correct_answer.'</span>';


    $wrong = 0;

    if($choosen_answer != $correct_answer) { // compare the 2 values

        $wrong++;

        echo '<span class="wrong text-danger">Wrong</span>';

    }

    else {

        echo '<span class="correct text-success">Correct</span>';

    }


}

echo count($wrong); // this should give me the number of wrong answers, but it does not...

我想计算错误答案的数量,我为此尝试了,但它没有给我错误答案的数量。count($wrong);


所以我需要什么:如果问题回答错误,它应该给我数字383


每个 txt 文件如下所示:


02 // 0 is the correct answer, 2 is the answer from the user. I compare 0 with 2. So wrong answer


14 // 1 is the correct answer. 4 is the answer of the user. I compare 1 with 4. So wrong answer


22 // 2 is the correct answer. 2 is also the answer of the user. So correct answer



至尊宝的传说
浏览 91回答 1
1回答

aluckdog

$wrong = 0;在前循环中!因此,在每次迭代之后,它再次使其为0。您的代码应如下所示:$wrong = 0;foreach($all_files as $file) {&nbsp; &nbsp; $each_file = file_get_contents($file);&nbsp; &nbsp; $choosen_answer = substr($each_file, -1); // last number is the number user has choosen&nbsp; &nbsp; $correct_answer = substr($each_file, 0,1); // first number is the correct answer&nbsp; &nbsp; // output the answers&nbsp; &nbsp; echo '<span class="choosen_answer">'.$choosen_answer.'</span>';&nbsp;&nbsp; &nbsp; echo '<span class="correct_answer">'.$correct_answer.'</span>';&nbsp; &nbsp; if($choosen_answer != $correct_answer) { // compare the 2 values&nbsp; &nbsp; &nbsp; &nbsp; $wrong++;&nbsp; &nbsp; &nbsp; &nbsp; echo '<span class="wrong text-danger">Wrong</span>';&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; echo '<span class="correct text-success">Correct</span>';&nbsp; &nbsp; }}echo $wrong;&nbsp;
随时随地看视频慕课网APP
我要回答