我很难用这段代码显示菜单。在父菜单中,我只显示“数组”而不是菜单名称。这是代码。
模型
function getCategoriesNav(){
//page 157
$data = array();
$this->db->select('id, name, parentid');
$this->db->where('status', 'active');
$this->db->order_by('parentid', 'asc');
$this->db->order_by('name', 'asc');
$this->db->group_by('parentid', 'id');
$Q = $this->db->get('categories');
if($Q->num_rows >0){
foreach($Q->result() as $row){
if($row->parentid > 0){
$data[0][$row->parentid]['children'][$row->id] = $row->name;
}else{
$data[0][$row->id]['name'] = $row->name;
}
}
}
$Q->free_result();
return $data;
}
控制器
function index()
{
$data['title'] = 'News';
$data['navlist'] = $this->MCats->getCategoriesNav();
$data['mainf'] = $this->MProducts->getMainFeature();
$skip = $data['mainf']['id'];
$data['sidef'] = $this->MProducts->getRandomProducts(3, $skip);
$data['main'] = 'home';
$this->load->vars($data);
$this->load->view('template');
}
并且视图是
<?php
if(count($navlist)){
echo "<ul>";
foreach($navlist as $key => $list){
foreach($list as $topkey => $toplist){
echo "<li class='cat'>";
echo anchor("welcome/cat/$topkey", $toplist);
echo "</li>\n";
if(count($toplist['children'])){
foreach($toplist['children'] as $subkey => $subname){
echo "\n<li class='subcat'>";
echo anchor("welcome/cat/$subkey", $subname);
echo "</li>";
}
}
}
}
echo "</ul>\n";
}
?>
请帮助
答案 0 :(得分:1)
这是我对你的数组结构的检查:
你有一个四级多维数组来保存行名。
[0] [parent id] ['children'] [row id] =行名。
您的foreach(navlist as key=>list)
将[父ID]设为$key
,['儿童'] [行ID] =行名称为$list
。
您的foreach($list as $topkey=>$toplist)
将['children']设置为$topkey
,[row id] =将行名称设为$toplist
。
您对anchor('welcome/cat/$topkey, $toplist)
的调用是向锚点辅助函数发送数组,这可能就是您看到“数组”输出到浏览器的原因。此函数仅接受“要显示的文本”参数的字符串。
修改强>
要回答您的评论,请在您的观点中尝试:
而不是:
echo anchor("welcome/cat/$topkey", $toplist);
使用此:
echo anchor("welcome/cat/$topkey", $toplist['name']);
现在,您将传递$data[0][$row->id]['name']
的值作为您的构造,以便在模型中保留$row->name
。
编辑2:
我也注意到你使用
if($Q->num_rows >0){
您缺少num_rows函数的括号。
if($Q->num_rows() > 0) {
这可能与您遗失的父母和子女类别有关。如果没有,我建议从查询中删除group_by()
子句,只是为了看看这是否会让你感到困扰。如果这些没有帮助,请继续删除order_by()
,看看会发生什么。