以特定方式格式化数组以在视图中显示

时间:2015-11-10 07:01:52

标签: php codeigniter model-view-controller

我有两个问题和答案表。 answer表将question表的主键作为外键。 我已使用连接查询重新检索数据,如下所示。

public function getData() {
    $this->db->select('*');
    $this->db->from('question');
    $this->db->join('answer', 'answer.question_id = question.question_id');
    $query = $this->db->get();
    return $query->result();
}

我想以下列方式格式化数组。并在视图中回显结果。

$question_array[question_number] = array(
    'question_text' =>$question,
    'answers'=>array(
        'answer1' =>$answer1,
        'answer2'=>$answer2,
    ),
);

编辑:

getData()函数返回以下内容

  array(1){
 [0]=> object(stdClass)#20 (6) {
 ["question_id"]=> string(1) "1" 
 ["question"]=> string(15) "What is my name" 
 ["type"]=> string(3) "mcq" 
 ["answer_id"]=> string(1) "1" ["answer"]=> string(6) "Lahiru" ["correct"]=> string(1) "C" } }

1 个答案:

答案 0 :(得分:0)

尝试如下:

   public function getData() {
       $this->db->select('*');
       $this->db->from('question');
       $this->db->join('answer', 'answer.question_id = question.question_id');
       $query = $this->db->get();
       $query_result = $query->result();
       $question_array = array(); 

       foreach ($query_result as $row) { 
           $temp = array();
           $temp['question_text'] = $row->question;

           //Change below line as its not clear from the returned array you mentioned
           $temp['answers'] = $row->answer;

           $question_array[$row->question_id] = $temp;
       }
       return $question_array;
   }