构建 2 个数组,其中一个是二维的
喜欢:
questionId question answer
1 sky has color? blue
1 sky has color? red
2 what is? answer 1
....
保存在这样的数组中:
$questions[1] = "sky has color?";
$answers[1][0] = "blue";
$answers[1][1] = "red";
$questions[2] = "what is?";
$answers[2][0] = "answer 1";
php:
$questions = array();
$answers = array();
// Take every row
while($qa = $getqa->fetch_assoc()) {
// Add questions
// $question[1] = "sky has color?";
$question[$qa['qid']] = $qa['question'];
// If no answers have been set yet, init an array
if (!is_array($answers[$qa['qid']]) {
$answers[$qa['qid']] = array();
}
// Add answers
// $answers[1][] = "blue";
// $answers[1][] = "red";
$answers[$qa['qid']][] = $qa['answer'];
}
然后循环它:
// Loop $questions array
foreach ($questions as $qid => $question) {
echo "<p>Question: " . $quesion . "</p>";
// Loop $answers[questionId] array
foreach ($answers[$qid] as $answer) {
echo $answer . "<br />";
}
}
这个答案可以改进,但应该可以工作并为您提供良好的启动。