我尝试使用子菜单构建动态菜单,以插入数据库中的链接。我将下面的代码直接编写到我的视图中进行测试,并且完美地运行了:
<?php
$this->db->from('categories');
$this->db->where('category_id_parent', 0);
$menu_list = $this->db->get();
foreach ($menu_list->result() as $menu): ?>
<li>
<a href=""><?php echo ucwords($menu->category_title) ?></a>
<?php
$cat_id = $menu->category_id;
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$submenu_list = $this->db->get();
?>
<ul>
<?php foreach ($submenu_list->result() as $submenu): ?>
<li>
<a href=""><?php echo ucwords($submenu->category_title) ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
所以我决定创建模型和控制器并使它们适应新视图。
我的模特:
public function get_menu() {
$query = $this->db->get_where('categories', array('category_id_parent' => 0));
if ($query->num_rows() > 0):
return $query;
endif;
}
public function get_submenu() {
$query = $this->db->get_where('categories', array('category_id_parent' => 0));
foreach ($query->result() as $row):
$cat_id = $row->category_id;
endforeach;
if ($cat_id != FALSE):
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$query = $this->db->get();
return $query;
else:
return FALSE;
endif;
}
控制器:
public function menu() {
$data['menu_list'] = $this->Menu_model->get_menu();
$data['submenu_list'] = $this->Menu_model->get_submenu();
$this->load->view('frontend/header', $data);
}
观点:
<?php foreach ($menu_list->result() as $menu): ?>
<li>
<a href="#" ><?php echo ucwords($menu->category_title) ?> </a>
<ul>
<?php foreach ($submenu_list->result() as $submenu): ?>
<li>
<a href="#"><?php echo ucwords($submenu->category_title) ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
除了重复相同链接的子菜单外,几乎所有内容都有效。我做错了什么?
答案 0 :(得分:0)
if ($cat_id != FALSE):
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$this->db->where('category_id !=', 0);
$query = $this->db->get();
return $query;
else:
die('I am here') ;
return FALSE;
endif;
在function get_submenu()
中尝试查看天气$cat_id
是否为空..
编辑:
也许就是这种情况,在您通过
运行的预告片代码中 foreach ($menu_list->result() as $menu)
然后传递$cat_id = $menu->category_id
,然后每次都会传出
$submenu_list
。在后一个版本中,您刚刚获取了记录
foreach ($query->result() as $row):
$cat_id = $row->category_id;
endforeach;
并且您没有在下面的循环中传递它,不应该在下面运行循环以获取$cat_id
的每个值,这是否有意义。 ?
if ($cat_id != FALSE):
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$this->db->where('category_id !=', 0);
$query = $this->db->get();
return $query;
else:
这是你需要遍历$ cat_id的块,因为这是一个数组。