使用2 foreach进行2次查询 - 如何一起使用它们

时间:2015-06-03 08:49:28

标签: codeigniter foreach

我必须进行统计 - 比较2个值。我做了2个查询。现在看起来像是:

http://prntscr.com/7ckcq2

这些进步的酒吧重复多次。每个问题应该只有一个进度条。 这些统计数据显示了调查结果。我必须将每个问题的学生的平均答案从调查分为所有填写调查问卷的学生的平均答案。我正在尝试为这两个查询创建2个foreach循环。但他们重复了很多次。我应该如何一起使用它们? 我正在使用CodeIgniter。我的观点是:

 public function average_results_show()
    {


        $data['dynamic_view'] = 'results/average_results';
        $data['average_student_result'] = $this->result_model->average_student_result();
        $data['average_result'] = $this->result_model->result_question();

        $this->load->view('templates/main',$data);  
    }

我的控制器是:

/* Show average answers of questions of a student */
    public function average_student_result()
    {           
        $this->db->select('survey_questions.question');
        $this->db->distinct('survey_questions.question_id');
        $this->db->select_avg('answer');
        $this->db->from('survey_answers');
        $this->db->join('survey_questions', 'survey_questions.question_id=
        survey_answers.question_id  ');
        $this->db->where('user_id', $this->session->userdata['user_id']);    
        $this->db->where('survey_id', $this->uri->segment(3));
        $this->db->group_by('survey_answers.question_id');
        $query=$this->db->get();
        return $query->result();

    }
    /* Show average answers of questions */
    public function result_question()
    {           
        $this->db->select('survey_questions.question');
        $this->db->distinct('survey_questions.question_id');
        $this->db->select_avg('answer');
        $this->db->from('survey_answers');
        $this->db->join('survey_questions', 'survey_questions.question_id=
        survey_answers.question_id  ');    
        $this->db->where('survey_id', $this->uri->segment(3));
        $this->db->group_by('survey_answers.question_id');
        $query=$this->db->get();
        return $query->result();

    }

我的模特是:

var responseDict = json!.objectForKey("data") as! NSDictionary
var idString = responseDict.objectForKey("id") as! String
var dueString = responseDict.objectForKey("due") as! String

1 个答案:

答案 0 :(得分:1)

从最顶层的foreach,你可以得到我觉得的问题ID。在$ average_student_result数组中,您将获得特定的学生回答问题数组,如

$average_student_result['question_id'] = 'answer average or answer'; //any value

所以我们可以避免像$average_student_result[$row->question_id]这样的内部foreach。所以你们每个学生都能得到明智的表现,而且整体学生也是明智的。我希望这个答案会有所帮助。