как рассчитать количество совпадений файлов с разными значениями в php - PullRequest
0 голосов
/ 14 января 2020

Для экзамена с несколькими вариантами я храню данные в .txt файлах.

У меня есть 8 .txt файлов, в которых хранится 2 или более чисел. Названия текстовых файлов: 1.txt, 2.txt, 3.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); для этого, но это не дает мне число неправильных ответов.

Итак, что мне нужно: если 3 из 8 вопросов, на которые даны неправильные ответы, это должно дать мне номер 3

Каждый текстовый файл выглядит так:

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 Ответ

1 голос
/ 14 января 2020

$wrong = 0; в foreach l oop! поэтому после каждой итерации он снова равен 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; 
...