How to group CodeIgniter query result data into an associative 3 level array
01:35 16 Oct 2015

Scenario:

I have course that has shifts(morning ,evening ect.) [course is parent of shift].
and for every shift there are sections (A Green,A blue ,B ect)[shift is parent of sections].

Graph:

enter image description here

CodeIgniter3 query builder script:

$this->db->select("sections.section_id,c.course_id,s.id as shift_id");
$this->db->from($this->_table);
$this->db->join('shift s', 's.id = sections.shift_id', 'left');
$this->db->join('courses c', 's.course_id = c.course_id', 'left');
$this->db->join('employees e', 'e.employee_id = sections.head_id', 'left');
$this->db->distinct();
$this->db->order_by('section_id', 'desc');
$this->db->where('c.course_id', $course_id);

Query result:

Array
(
    [0] => Array
        (
            [course_id] => 3
            [section_id] => 5
            [shift_id] => 7
        )

[1] => Array
    (
        [course_id] => 2
        [section_id] => 4
        [shift_id] => 5
    )

[2] => Array
    (
        [course_id] => 2
        [section_id] => 3
        [shift_id] => 6
    )

[3] => Array
    (
        [course_id] => 1
        [section_id] => 2
        [shift_id] => 4
    )

[4] => Array
    (
        [course_id] => 1
        [section_id] => 1
        [shift_id] => 4
    )

)

Desired result:

Array
(
    [course_id 3] => Array
    (
        [shift id] => Array
        (
            [section_id] => 5
        )
    )
    [course_id 2] => Array
    (
        [shift_morning] => Array
        (
            [section_id] => 4
        )
        [shift_noon] => Array
        (
            [section_id] => 3
        )
    )
    [course_id 1] => Array
    (
        [shift_morning] =>array
        (
            [section_id] => 2
        )
        [shift_noon] =>array
        (
            [section_id] => 1
        )
    )
)
php mysql codeigniter join grouping