Если утверждение не проходит через массив ответов, скорее только чтение сначала - PullRequest
0 голосов
/ 03 мая 2018

недавно я добавил оператор печати в оператор if, объявляющий, что если пользователь ввел правильный ответ для текущего отображаемого вопроса, напечатайте ответ пользователя, если он правильный, и распечатайте исходный ответ на вопрос. Для того, чтобы сделать это, так как у меня есть такой массив:

$questionsAndAnwsers = array(array("question" => " What early cartoon character created by the Disney Studio was Mickey Mouse based off of ?", "answer" => "Oswald the Lucky Rabbit"),

                       array("question" => "Who invented the first TV ? Please use full name.", "answer" => "Philo Taylor Farnsworth"));

Я объявил текущий ответ равным текущему вопросу и ответу:

$currentAnswer = $questionsAndAnwsers[$currentQuestion]["answer"];

После этого я, наконец, настроил оператор if для выполнения фактической проверки, и именно здесь я знаю, что он не работает с моими настройками, потому что он больше не проверяет ответ правильно, и как только появляется второй вопрос, он неверен даже с правильным ответом. Вот мое заявление if:

if($_POST["guess"] == $currentAnswer){
     $currentQuestion++;
     $guess = $_POST['guess'];
     print ("Your answer: $guess <br>"); 
     print("The answer expected: $currentAnswer<br>");  
     print("Answer Correct<br>");
     print("Next Question Below<br>");
   } 
   else {
     $currentQuestion=0;
     $guess = $_POST['guess'];
     print ("Your answer: $guess <br>");   
     print("You have failed..<br>"); 
   }

После реализации любого вопроса после того, как первый отказал, я думаю, что моя установка для текущего ответа не верна, и все, что он вызывает, возможно, является первым ответом в наборе, который является огромной проблемой, так как мне нужен ответ, чтобы меняется с каждым новым вопросом. Я думал, что понял это, и это сработает, но я либо делаю простую ошибку, либо я неправильно понимаю, что мне нужно делать.

Есть ли у кого-нибудь совет, как получить текущий ответ, равный каждому отдельному ответу при изменении вопросов.

Полный код (только для справки):

<html>
<head>
<style>
#main{
  font-family:"Times New Roman", Times, serif; 
  font-size:2em;
  text-align:center;
}
</style>
</head>
<body>
<?php
$questionsAndAnwsers = array(array("question" => " What early cartoon character created by the Disney Studio was Mickey Mouse based off of ?",  "answer" => "Oswald the Lucky Rabbit"),

array("question" => "Who invented the first TV ? Please use full name.", "answer" => "Philo Taylor Farnsworth"),

array("question" => "When was Warner Brothers founded ? Format: Month Day, Year", "answer" => "April 4, 1923"), 

array("question" => "When was Superman's first appearance date ? Format: Month Year", "answer" => "June 1938"),

array("question" => "What does the acronym OWN, for the cable television channel, stand for ?", "answer" => "Oprah Winfrey Network"),

array("question" => "What type of dog is Scooby Doo from the cartoon series, Scooby Doo ?", "answer" => "Great Dane"),

array("question" => "What type of food does Garfield the cat love ?", "answer" => "Lasagna"), 

array("question" => "How many Pokemon were in Generation I ?", "answer" => "151"), 

array("question" => "What popular cartoon/show is Woodstock from ?", "answer" => "Peanuts"), 

array("question" => "What was Jim Henson's first puppet series back in 1955 ?", "answer" => "Sam and Friends"), 

array("question" => "Who created the Mighty Morphin Power Rangers ?", "answer" => "Haim Saban"), 

array("question" => "How many Back to the Future movies were there ?", "answer" => "3"), 

array("question" => "What football quarterback had a short-lived television show that premiered in 1969 ?", "answer" => "Joe Namath"),

array("question" => "Where there any R rated movies in 1961 ?", "answer" => "No"), 

array("question" => "In what year did the animal-documentary series Wild Kingdom premiere ?", "answer" => "1963"), 

array("question" => "What sit-com was about two bumbling police men and their squad car ?", "answer" => "Car 54, Where Are You")); 


// current question
$currentQuestion = 0;
$currentAnswer = $questionsAndAnwsers[$currentQuestion]["answer"];

if(isset($_POST["currentQuestion"])){
     $currentQuestion = $_POST["currentQuestion"];

     if($currentQuestion==15){
        header("Location:  http://students.purchase.edu/martin.mcnicholas/scriptingfortheweb/index2.html"); /* Redirect browser */
        exit();
     }else if($_POST["guess"] == $currentAnswer){
         $currentQuestion++;
         $guess = $_POST['guess'];
         print ("Your answer: $guess <br>"); 
         print("The answer expected: $currentAnswer<br>");  
         print("Answer Correct<br>");
         print("Next Question Below<br>");
       } 
       else {
         $currentQuestion=0;
         $guess = $_POST['guess'];
         print ("Your answer: $guess <br>");   
         print("You have failed..<br>"); 
       }
    }
?>


<div id=main>
<br><br><br><br>
<form method="POST" action="">
    <label for="question"><?php echo ($currentQuestion+1).". ".   $questionsAndAnwsers[$currentQuestion]["question"];
    ?></label>

    <input type="hidden" name="currentQuestion" value="<?php echo     $currentQuestion;?>">
    <input type="text" name="guess" value="" placeholder="Answer...">
    <input type="submit" value="Next Question">
</form>
</div>
</body>
</html>

1 Ответ

0 голосов
/ 03 мая 2018

вам необходимо переопределить переменную $currentAnswer, если было отправлено $_POST["currentQuestion"]. В противном случае $currentAnswer всегда будет установлено на 0 (поэтому работает только первый ответ).

if(isset($_POST["currentQuestion"])){
     $currentQuestion = $_POST["currentQuestion"];

     //Add this line
     $currentAnswer = $questionsAndAnwsers[$currentQuestion]["answer"]
     //Continue your code here

     if($currentQuestion==15){
        header("Location:  http://students.purchase.edu/martin.mcnicholas/scriptingfortheweb/index2.html"); /* Redirect browser */
        exit();
     }else if($_POST["guess"] == $currentAnswer){
         $currentQuestion++;
         $guess = $_POST['guess'];
         print ("Your answer: $guess <br>"); 
         print("The answer expected: $currentAnswer<br>");  
         print("Answer Correct<br>");
         print("Next Question Below<br>");
       } 
       else {
         $currentQuestion=0;
         $guess = $_POST['guess'];
         print ("Your answer: $guess <br>");   
         print("You have failed..<br>"); 
       }
    }

Также было бы неплохо проверить, действительно ли существует индекс массива $questionsAndAnwsers и ответы:

if(isset($_POST["currentQuestion"])){
     $currentQuestion = $_POST["currentQuestion"];
     if(isset($questionsAndAnwsers[$currentQuestion])){
       $currentAnswer = $questionsAndAnwsers[$currentQuestion]["answer"]
       if($currentQuestion==15){
          header("Location:  http://students.purchase.edu/martin.mcnicholas/scriptingfortheweb/index2.html"); /* Redirect browser */
          exit();
       }else if($_POST["guess"] == $currentAnswer){
           $currentQuestion++;
           $guess = $_POST['guess'];
           print ("Your answer: $guess <br>"); 
           print("The answer expected: $currentAnswer<br>");  
           print("Answer Correct<br>");
           print("Next Question Below<br>");
         } 
         else {
           $currentQuestion=0;
           $guess = $_POST['guess'];
           print ("Your answer: $guess <br>");   
           print("You have failed..<br>"); 
         }       
     }else{
       //Do some error handling here 
       exit("Question not found!");
     }

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...