2 回答
TA贡献1844条经验 获得超8个赞
尝试以下
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
应该是空的
TA贡献1821条经验 获得超6个赞
我根据您的需要创建了一个演示,它对我有用。我正在分享下面的代码,我已经在必要时在评论中进行了解释。看看它是否对你有帮助。
控制器
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
- 2 回答
- 0 关注
- 108 浏览
添加回答
举报