我正在查询类别表id, parent_id, name
,以生成所有类别和子类别的列表视图。到目前为止,我拥有的是:
- HP
- 笔记本电脑
- PC
- 体育
- 太阳镜
- 食物
- House
我用来生成输出的函数是:
public function get_category($parent_id = NULL)
{
$query = $this->db->get_where('category', array('parent_id' => $parent_id))->result();
$result = '';
foreach ($query as $row)
{
$i = 0;
if ($i == 0)
{
$result .= '<ul>';
}
$result .= '<li><a href="'.base_url().'category/edit/'.$row->id.'">' . $row->name;
$result .= $this->get_category($row->id);
$result .= '</li>';
$i++;
if ($i > 0)
{
$result .= '</ul>';
}
}
return $result;
}
这就是我想要实现的:
HP
HP > Laptops
HP > PC
Sports
Sports > Sunglasses
Food
House
尝试以下
public function get_category($parent_id = NULL,$level, $prev = "")
{
$query = $this->db->get_where('category', array('parent_id' => $parent_id))->result();
$result = '';
foreach ($query as $row)
{
$temp = $prev;
if($level == 0){
$temp .= '<a href="'.base_url().'category/edit/'.$row->id.'">' . $row->name.'</a>';
}else{
$temp .= ' > <a href="'.base_url().'category/edit/'.$row->id.'">' . $row->name.'</a>';
}
$result .= $temp;
$result .= "<br />";
$result .= $this->get_category($row->id, $level + 1, $temp);
}
return $result;
}
此功能的第一次运行应该是
get_category(NULL, 0, "");
此处
NULL
是父id(您可以使用循环来动态地传递id(level
应为0
prev
应为空
我已经根据您的需求创建了一个演示,它对我很有效。我正在分享下面的代码,我已经在必要的地方在评论中进行了解释。看看它是否对你有帮助
控制器
public function get_category($parent_id = NULL){
// get the {category}, {sub_category} from the table, if {sub_category} stored in different table use {JOIN}
$data['category'] = $this->db->get_where('category', array('parent_id' => $parent_id))->result();
$this->load->view('your-view', $data);
}
查看
<?php
if(!empty($category)){ // check if {$category} has value; if not, do nothing
$catArr = array(); // initialize array to store category id
?>
<ul> <!-- Start ul -->
<?php
foreach($category as $cat){ //loop through all the {category} array
// check if the {cat_id} already exists in array; if not, do so where {cat_id} is category id(change your value here)
if( ! in_array( $cat->cat_id, $catArr ) ){
$catArr[] = $cat->event_id;
?>
<li><?php echo $cat->cat_name; ?></li> <!-- show {cat_name} in list -- your category name here -->
<?php
}
?>
<!-- Show {cat_name} and {subcat_name} both -- (your values here). Give links or whatever here(your styling)-->
<li><?php echo $cat->cat_name; ?> > <?php echo $cat->subcat_name; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
输出
Honda Honda > Car Honda > Bike Philips Philips > Electricals Philips > Electronics