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


formatting an array in specific way to show in a view

我有两个问答表。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" 
 ["answerswer_id"]=> string(1) "1" ["answerswer"]=> string(6) "Lahiru" ["correct"]=> string(1) "C" } }

尝试如下:

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