数组每次进入两次

时间:2014-07-26 16:16:34

标签: php arrays codeigniter loops

我有一个模型,它具有查询学生注册的科目的功能。

public function getAllSubjects($username){
    $this->db->select('student.username, subjects.subject_name, teacher.firstname as TeachersFirstName, teacher.surname as TeacherSurname');
    $this->db->from('users student');
    $this->db->join('student_subjects', 'student.username = student_subjects.student_username', 'inner');
    $this->db->join('subjects', 'student_subjects.subject_id = subjects.subject_id', 'inner');
    $this->db->join('users teacher', 'subjects.teacher_username = teacher.username', 'inner');
    $this->db->where('student.username', $username);
    $studentSubjQuery = $this->db->get('users');
    return $studentSubjQuery->result_array();
}

在控制器中,我从模型中调用函数并将返回的数组存储到数据中并将其传递给视图。现在,当我尝试打印数组时,行会在数组中存储两次。这是打印的数组:

    Array
(
    [0] => Array
        (
            [username] => dirkjan021
            [subject_name] => Chemistry
            [TeachersFirstName] => Teacher 1
            [TeacherSurname] => Teacher 1 Surname
        )

    [1] => Array
        (
            [username] => dirkjan021
            [subject_name] => Chemistry
            [TeachersFirstName] => Teacher 1
            [TeacherSurname] => Teacher 1 Surname
        )

    [2] => Array
        (
            [username] => dirkjan021
            [subject_name] => Physics
            [TeachersFirstName] => Teacher 1
            [TeacherSurname] => Teacher 1 Surname
        )

    [3] => Array
        (
            [username] => dirkjan021
            [subject_name] => Physics
            [TeachersFirstName] => Teacher 1
            [TeacherSurname] => Teacher 1 Surname
        )

)

这是控制器代码:

public function acads()
{
    if (!$this->session->userdata('username')) {
        // Redirect to homepage
        redirect('../');
    } else {
        // Allow Access to User's Acads
        $data['userInfo'] = $this->session->all_userdata();
        // Query User Subjects
        $this->load->model('usersubject_model');
        $data['userSubjects'] = $this->usersubject_model->getAllSubjects($this->session->userdata('username'));
        $this->load->view('view_userAcads', $data);
    }
}

更新 以下是根据'$ this-> output-> profiler(TRUE)'的查询:

SELECT `student`.`username`, `subjects`.`subject_name`, `teacher`.`firstname` as TeachersFirstName, `teacher`.`surname` as TeacherSurname
FROM (`users` student, `users`)
INNER JOIN `student_subjects` ON `student`.`username` = `student_subjects`.`student_username`
INNER JOIN `subjects` ON `student_subjects`.`subject_id` = `subjects`.`subject_id`
INNER JOIN `users` teacher ON `subjects`.`teacher_username` = `teacher`.`username`
WHERE `student`.`username` =  'dirkjan021' 

1 个答案:

答案 0 :(得分:2)

我现在明白了。最初的模型查询"查询两次" FROM('用户'学生,'用户')因为我有这两行: $this->db->from('users' student); $this->db->get('users');

我做的是删除了db->并将db->get编辑为db->get('users' student);