父子关系树需要递归函数?

时间:2015-10-16 07:17:39

标签: php mysql join foreach codeigniter-3

  

情景:

我的课程有变化(早上,晚上等)[当然是轮班的父母]。
并且对于每个班次都有部分(绿色,蓝色,等等)[班次是部分的父母]。

  

图:

enter image description here

我加入的当前记录:

    $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);
  

查询结果:

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
    )

)

想要这样的结果:

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
                            )
    )
)

任何可以帮助的人。

1 个答案:

答案 0 :(得分:0)

我无法推断所需的信息,无法从发布的信息中正确设置Shift键,但您只需修改switch语句即可正确设置此键:

$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 = $this->db->get();

$results = array();
foreach ($query->result_array() as $row) {
    switch ($row['shift_id']) {
        case 5:
            $shift = 'morning';
        break;

        case 6:
            $shift = 'noon';
        break;
    }

    $results['course_id '.$row['course_id']]['shift_'.$shift]['section_id'] = $row['section_id'];
}