为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
至尊宝的传说 2022-08-05 09:32:43
对于多项选择考试,我将数据存储在文件中。.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
查看完整描述

1 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

$wrong = 0;在前循环中!因此,在每次迭代之后,它再次使其为0。


您的代码应如下所示:


$wrong = 0;

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>';


    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 $wrong; 


查看完整回答
反对 回复 2022-08-05
  • 1 回答
  • 0 关注
  • 90 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信