codeigniter中的N层导航

时间:2016-08-26 11:34:05

标签: codeigniter

如何在代码点火器中创建顶部导航?

1 个答案:

答案 0 :(得分:0)

在控制器中,我声明了一个函数并调用模型

private function getNavigation(){
    $this->load->model('xx');
    $data['nav'] = $this->xx->prepareTree();
    $this->load->view('index',$data);
}

在模型中我宣布了三个函数

public function prepareTree(){
    $this->db->select("`catalog_parent` as parent_id, `catalog_name` as menu_item, `catalog_id` as id, `catalog_template` as pager_id");
    $this->db->from("catalog_category");
    $this->db->where("`catalog_navigation` = '1'");
    $this->q = $this->db->get();
    $create = '';
    if ($this->q->num_rows() > 0) {
       $create = $this->prepareList($this->q->result_array());
    }
    if(!empty($create)){
        return $this->category_tree($create);
    } else {
        return '';
    }
 }

 private function prepareList(array $items, $pid = 0) {
    $output = array();
    foreach ($items as $item) {
        if ((int) $item['parent_id'] == $pid) {
            if ($children = $this->prepareList($items, $item['id'])) {
                $item['children'] = $children;
            }
            $output[] = $item;
        }
    }
    return $output;
}

private function category_tree($menu_items, $child = false){
    $output = '';
    if (count($menu_items)>0) {
        $output .= ($child === false) ? '<ul id="main-menu" class="sm sm-blue">' : '<ul>' ;

        foreach ($menu_items as $item) {
            $output .= '<li>';
            $output .= '<a href="#">'.$item['menu_item'].'</a>';
            if (isset($item['children']) && count($item['children'])) {
                $output .= $this->category_tree($item['children'], true);
            }
            $output .= '</li>';
        }
        $output .= '</ul>';
    }
    return $output;
}

如果有人建议更简单的方法,请向我们提出建议。 感谢