Динамически создавать и заполнять входное радио с помощью PHP

В настоящее время я работаю с PHP и HTML, я делаю несколько выборочных экзаменов, PHP-файл содержит четыре массива, первый хранит вопросы, второй хранит вероятные ответы для опции «a» », третий хранит вероятные ответы для опции «b»), и, наконец, последний хранит ответы для опции «c» "

Вот его код для создания и заполнения как вопросов, так и нескольких вариантов.

for($i=0; $i<20; $i++){ echo "$i.".$preguntas[$i]."<BR>"; echo"<input type = 'radio' name='R$i'>a)".$r1[$i]."<br>"; echo"<input type = 'radio' name='R$i'>b)".$r2[$i]."<br>"; echo"<input type = 'radio' name='R$i'>c)".$r3[$i]."<br>"; echo "<BR><BR>"; } 

У меня возникли некоторые проблемы, чтобы сделать эту работу, любую идею, как coud я оцениваю правильные ответы

заранее спасибо

 <html> <body> <form method="post"> <?php echo "<pre>"; var_export($_POST['R']); echo "</pre>"; for($i=0; $i<20; $i++){ echo "$i.".$preguntas[$i]."<BR>"; echo"<input type='radio' name='R[$i]' value='a'>a){$r1[$i]}<br>"; echo"<input type='radio' name='R[$i]' value='b'>b){$r2[$i]}<br>"; echo"<input type='radio' name='R[$i]' value='c'>c){$r3[$i]}<br>"; echo "<BR><BR>"; } ?> <button>submit</button> </form> </body> </html> 

Вы получите что-то вроде:

 array ( 0 => 'a', 1 => 'b', 2 => 'b', ) 

Например:

 <html> <body> <form method="post"> <?php $questions = [ [ 'question' => 'Who was first programmer?', 'answers' => [ 'a' => 'Alan Turing', 'b' => 'Ada Lovelace', 'c' => 'Rasmus Lerdorf', 'd' => 'James Bond', ], 'correctAnswer' => 'b', ], [ 'question' => 'Who created php?', 'answers' => [ 'a' => 'Alan Turing', 'b' => 'Ada Lovelace', 'c' => 'Rasmus Lerdorf', ], 'correctAnswer' => 'c', ], [ 'question' => 'Who created Turing machine?', 'answers' => [ 'a' => 'David Beckham', 'b' => 'Rasmus Lerdorf', 'c' => 'Floyd Mayweather, Jr.', 'd' => 'Ada Lovelace', 'e' => 'Alan Turing', ], 'correctAnswer' => 'e', ], ]; if (!empty($_POST['response'])) { foreach ($_POST['response'] as $questionId => $answerKey) { echo '<h5>'.$questions[$questionId]['question'].'</h5>'; if ($questions[$questionId]['correctAnswer'] === $answerKey) { echo 'Correct answer.<br>'; } else { echo 'Wrong answer.<br>'; } } } else { foreach ($questions as $questionId => $data) { echo '<h5>'.$data['question'].'</h5>'; foreach ($data['answers'] as $key => $answer) { echo '<input type="radio" name="response['.$questionId.']" value="'.$key.'">'.$key.') '.$answer.'<br>'; } echo "<br><br>"; } } ?> <button>submit</button> </form> </body> </html> 

Вы можете настроить его здесь

Я думаю, вы должны сделать это так:

 foreach ($preguntas as $key => $pregunta) { echo ($key + 1) . '. ' . $pregunta . '<br />'; for ($i = 1; $i <= 3; $i++) { echo '<input type="radio" name="answerForQuestion' . $key . '" value="' . ${'r' . $i}[$key] . '" /><br />' } echo '<br /><br />'; } 

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

Это мое решение для вашей проблемы. См. Комментарии (я объяснил, что делает каждая его часть) и попытайтесь понять это.

 <?php // Set questions and answers $questions = array( // First question array( 'question' => 'Question 1?', // Possible answers for first question 'answers' => array( array( 'answer' => 'Answer option 1', 'correct' => false ), array( 'answer' => 'Answer option 2', 'correct' => true ), array( 'answer' => 'Answer option 3', 'correct' => false ), ) ), // Second question array( 'question' => 'Question 2?', // Possible answers for second question 'answers' => array( array( 'answer' => 'Answer option 1', 'correct' => false ), array( 'answer' => 'Answer option 2', 'correct' => false ), array( 'answer' => 'Answer option 3', 'correct' => true ), ) ) ); // Print form echo '<form method="POST">'; $i = 1; foreach ($questions as $question_key => $questionArray) { echo $i.'. '.$questionArray['question'].'<br />'; // Answers will be POSTed in one array (answerForQuestion) // answerForQuestion array keys would be questions keys. // Values would be keys to our answers array. // So we can easily check for correct answers. See below. foreach ($questionArray['answers'] as $answer_key => $answerArray) { echo '<input id="question_'.$question_key.'_'.$answer_key.'" type="radio" name="answerForQuestion['.$question_key.']" value="'.$answer_key.'"> <label for="question_'.$question_key.'_'.$answer_key.'">'.$answerArray['answer'].'</label><br />'; } echo '<br /><br />'; // Increase questions order number. $i++; } echo '<input type="submit" name="go" value="Answer!">'; echo '</form>'; // Check for answers, if user POSTed data. if($_POST['go']){ // Get count of questions $questionsCount = count($questions); // This will be increased with correct answer $correctAnswersCount = 0; // Check for every question. // This will quarantee that empty answer will be considered as false. // Assuming that every question has correct answer. foreach ($questions as $question_key => $questionArray) { // Get answer key. Key of our array, so we can easily find selected answer $answer_key = $_POST['answerForQuestion'][$question_key]; // Get selected answer array $answerArray = $questionArray['answers'][$answer_key]; // If is correct if($answerArray['correct']){ echo 'Your answer for question "'.$questionArray['question'].'" is correct!<br />'; $correctAnswersCount++; } else{ echo 'Your answer for question "'.$questionArray['question'].'" is incorrect!<br />'; } } // Just for statistics. Not in your question, but wount hurt echo '<br />Correct answers: '.$correctAnswersCount.' out of '.$questionsCount.'. Result: '.round($correctAnswersCount / $questionsCount * 100).'%'; } ?>