我即将做一个简单的测验。 我不想在一个页面中打印所有问题,格式良好的布局如下:
问题1
答案1
答案2
问题2
答案1
答案2
我正在研究以下代码:
$get_qa = $mysqli->query("
SELECT
a.question AS question,
a.id AS qid,
b.answer AS answer,
b.qid AS aqid (related to: question id)
FROM rw_questions a
LEFT OUTER JOIN rw_qanswers b ON a.id = b.qid");
while($qa = $getqa->fetch_assoc()){
echo $qa['question'].$qa['answer'];
}
这会导致列表混乱。但是我如何改进这个,就像我在顶部写的那样? 任何帮助都很酷! 我猜我需要用foreach或类似的东西来改进它吗?
答案 0 :(得分:1)
构建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 />";
}
}
这个答案可以改进,但应该有效,并给你一个良好的kickstart。
答案 1 :(得分:0)
这实际上回答了我的问题: PHP & MYSQL: using group by for categories
我确信DanForm德国的解决方案有效,如果我有时间稍微调整一下:)