0

我要做一个简单的测验。我不想将所有问题都打印在一个页面中,并使用格式正确的布局,例如:

问题 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 或类似的东西来改进它?

4

2 回答 2

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 />";
    }
}

这个答案可以改进,但应该可以工作并为您提供良好的启动。

于 2013-07-17T13:07:54.770 回答
0

这实际上回答了我的问题: PHP & MYSQL: using group by for categories

我确信 DanFromGermany 的解决方案有效,如果我有时间稍微调整一下 :)

于 2013-07-19T12:27:42.200 回答