2 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
嘗試以下
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;
}
這個(gè)函數(shù)的第一次運(yùn)行應(yīng)該是
get_category(NULL, 0, "");
這里
NULL
是父 ID(您可以使用循環(huán)動(dòng)態(tài)傳遞 ID)level
應(yīng)該0
prev
應(yīng)該是空的

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
我根據(jù)您的需要?jiǎng)?chuàng)建了一個(gè)演示,它對(duì)我有用。我正在分享下面的代碼,我已經(jīng)在必要時(shí)在評(píng)論中進(jìn)行了解釋。看看它是否對(duì)你有幫助。
控制器
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 關(guān)注
- 139 瀏覽
添加回答
舉報(bào)