You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter3测验应用:如何将MySQL查询结果转为嵌套问答结构?

实现CodeIgniter 3中测验题数据的嵌套结构转换

我使用CodeIgniter 3开发了一款测验应用,需要从MySQL的quiz_table、question_table和answer_table三张表中获取4道测验题及其选项数据。当前的查询方法代码如下:

function getSingleQuizQuestionDataFromDB($quizId)
{
    try {
        $this->db->select('answer_table.quizId');
        $this->db->select('answer_table.questionId');
        $this->db->select('question_table.questionTitle');
        $this->db->select('question_table.correctAnswer');
        $this->db->select('answer_table.answerId');
        $this->db->select('answer_table.answer');
        $this->db->from('answer_table');
        $this->db->where('answer_table.quizId',$quizId);
        $this->db->join('question_table','answer_table.questionId= question_table.questionId','LEFT');
     
        //$this->db->group_by(['answer_table.quizId', 'answer_table.questionId']);
        $result = $this->db->get();

        $singleQuizQuestionData= $result->result_array();
        return $singleQuizQuestionData;
    } catch (Exception $e) {
        // log_message('error: ',$e->getMessage());
        return;
    }
}

当前返回的平级结构数据如下:

{
 "singleQuizQuestionData": [
  {
     "quizId": "68",
     "questionId": "76",
     "questionTitle": "q1q1",
     "correctAnswer": "q1a",
     "answerId": "269",
     "answer": "q1q1a1"
  },
  // 省略其余重复结构数据
 ]
}

我希望将同一问题的公共字段提取出来,把对应选项嵌套为answers数组,形成如下的嵌套数据结构(覆盖全部4题):

{
 "singleQuizQuestionData": [
   {
     "quizId": "68",
     "questionId": "76",
     "questionTitle": "q1q1",
     "correctAnswer": "q1a",
     "answers":[
     {
       "answerId": "269","answer": "q1q1a1"
     },
     // 省略其余选项数据
     ]
   }
 ]
}

请问是否可以实现这种数据结构转换?


解决方案

完全可以实现,只需要在获取数据库返回的平级数据后,通过PHP代码对结果进行重组即可。修改后的函数代码如下:

function getSingleQuizQuestionDataFromDB($quizId)
{
    try {
        $this->db->select('answer_table.quizId');
        $this->db->select('answer_table.questionId');
        $this->db->select('question_table.questionTitle');
        $this->db->select('question_table.correctAnswer');
        $this->db->select('answer_table.answerId');
        $this->db->select('answer_table.answer');
        $this->db->from('answer_table');
        $this->db->where('answer_table.quizId',$quizId);
        $this->db->join('question_table','answer_table.questionId= question_table.questionId','LEFT');
     
        $result = $this->db->get();
        $flatData = $result->result_array();

        // 初始化结构化数据数组
        $structuredData = [];

        foreach ($flatData as $row) {
            $questionId = $row['questionId'];
            
            // 如果当前问题还未加入结构化数据,先创建基础结构
            if (!isset($structuredData[$questionId])) {
                $structuredData[$questionId] = [
                    'quizId' => $row['quizId'],
                    'questionId' => $row['questionId'],
                    'questionTitle' => $row['questionTitle'],
                    'correctAnswer' => $row['correctAnswer'],
                    'answers' => []
                ];
            }

            // 将当前选项添加到对应问题的answers数组中
            $structuredData[$questionId]['answers'][] = [
                'answerId' => $row['answerId'],
                'answer' => $row['answer']
            ];
        }

        // 转换为索引数组(去掉questionId作为键的关联结构)
        $singleQuizQuestionData = array_values($structuredData);

        return $singleQuizQuestionData;
    } catch (Exception $e) {
        log_message('error', $e->getMessage());
        return [];
    }
}

逻辑说明

  • 遍历数据库返回的平级数据,以questionId作为分组标识,确保每个问题只生成一个基础结构
  • 将每个问题的公共字段(quizId、questionId、questionTitle、correctAnswer)只存储一次
  • 把同一问题的所有选项收集到对应的answers数组中
  • 最后通过array_values()将关联数组转换为索引数组,符合你期望的输出格式

内容的提问来源于stack exchange,提问作者Kavishka Rajapakshe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 12:30:55