且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从mySQL和PHP中将结果检索为多维数组?

更新时间:2023-02-23 11:07:43

您不能仅使用mysql检索多维数组(至少据我所知).您将必须进行一些php处理.这听起来并不疯狂.

You can't retrieve a multi-dimensional array purely with mysql (at least as far as I know). You will have to do some php processing. This doesn't sound too crazy.

首先,通过使用问题ID在quiz_questions上加入quiz_answers来更新查询以同时选择答案.然后,在您的循环中:

First, update your query to select answers at the same time by joining quiz_answers on quiz_questions using the question ID. Then, in your loop:

$quiz = array();
while ($row = mysql_fetch_assoc($result)) {
   // you don't need to check num_rows
   // fetch_assoc returns false after the last row, so you can do this
   // which is cleaner
   if (!isset($quiz[$row['question_id'])) {
      $quiz[$row['question_id']] = array(
         'question' => $row['question_text']
         , 'answers' => array()
      );
   }
   $quiz[$row['question_id']]['answers'][] = $row['answer_text'];
}
$full = json_encode(array('questions' => $quiz'));

这将为您提供经过json编码后的所需数组.

This will give you the array you want after it's json encoded.

请注意,您最终将每个答案选择一次问题文本/ID,这效率低下.您可以在答案上使用GROUP_CONCAT,但以上内容仍然几乎可以正常使用,只需拆分答案字符串即可.

Note that you will end up selecting the question text/id once per each answer, which is inefficient. You can use GROUP_CONCAT on the answers, but the above will still work almost identically, you just have to split the answer string.

我还建议您在mysql_*上使用PDO或其他包装器.

I also suggest you use PDO or some other wrapper over mysql_*.