以下是类别表
我的模特
public function get_categories($parent_id = 0){
$query = $this->db->where('parent_id', $parent_id)
->order_by('cat_name', 'ASC')
->get('category');
$return = array();
foreach ($query->result() as $category){
$return[$category->cat_id] = $category;
}
if($query->num_rows() > 0){
foreach ($query->result() as $cat){
$return[$cat->cat_id] = $cat;
}
return $return;
}
return $return;
}
我的观点
<div class="navbar-collapse collapse" id="navigation">
<ul class="nav navbar-nav navbar-left">
<li class="active">
<a href="<?php echo base_url();?>member/home">Home</a>
</li>
<?php foreach ($categories as $row): ?>
<li><a href="#"><?php echo $row->cat_name; ?></a></li>
<ul class="dropdown-menu">
<li><a href="#"><?php echo $row->cat_name; ?></a></li>
</ul>
<?php endforeach; ?>
</ul>
</div>
我想将磁盘作为孩子显示,因为没有显示。我的错误在哪里?请帮帮我
答案 0 :(得分:0)
你必须构建你的数据(说实话,你应该研究这段代码,因为你应该理解它)
使用以下代码修改模型:
public function get_categories()
{
$query = $this->db->order_by('cat_name', 'ASC')->get('category');
$arrData = $query->result();
$arrTreeById = [];
foreach($arrData AS $objItem)
{
$arrTreeById[$objItem->cat_id] = $objItem;
$objItem->arrChilds = [];
}
$arrChildIds = [];
foreach($arrTreeById AS $objItem)
{
if (isset($arrTreeById[$objItem->parent_id]))
{
$arrTreeById[$objItem->parent_id]->arrChilds[] = $objItem;
$arrChildIds[] = $objItem->cat_id;
}
}
array_walk($arrChildIds, function($val) use (&$arrTreeById) {
unset($arrTreeById[$val]);
});
return $arrTreeById;
}
和您的观点
<div class="navbar-collapse collapse" id="navigation">
<ul class="nav navbar-nav navbar-left">
<li class="active">
<a href="<?php echo base_url();?>member/home">Home</a>
</li>
<?php foreach ($categories as $row): ?>
<li><a href="#"><?php echo $row->cat_name; ?></a>
<?php
if (count($row->arrChilds) > 0) :
?>
<ul class="dropdown-menu">
<?php
foreach ($row->arrChilds as $row) :
?>
<li><a href="#"><?php echo $row->cat_name; ?></a></li>
<?php
endforeach;
?>
</ul>
<?php
endif;
?>
</li>
<?php endforeach; ?>
</ul>
</div>