我尝试在这个问题上实现@Tomas 答案 > PHP foreach create menu from array
我有下面的模型:
<?php
class Menu_model extends CI_Model{
function __construct(){
parent::__construct();
$this->load->database();
}
function getCategory($lang){
$sql = "SELECT * FROM category WHERE category.lang='".mysql_real_escape_string($lang)."'";
$result = $this->db->query($sql);
return $result;
}
function getSubCategory($lang){
$sql = "SELECT * FROM subcategory WHERE subcategory.lang='".mysql_real_escape_string($lang)."'";
$result = $this->db->query($sql);
return $result;
}
}
?>
然后我使用这个控制器来抛出数据:
<?php
$_SESSION['lang'] = 'EN';
class Home extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->database();
$this->load->model("menu_model");
}
public function index()
{
$data["category"] = $this->menu_model->getCategory($_SESSION['lang']);
$data["subcategory"] = $this->menu_model->getSubCategory($_SESSION['lang']);
$this->load->view('leftmenu_view',$data);//Left Menu
}
}
这是我显示菜单的视图:
<?php
foreach($category->result() as $menu){
echo "<li><a class=\"sf-with-ul\" href=\"category/".$menu->urlcategory."\">".$menu->namecategory."</a></li>";
foreach($subcategory->result() as $key=>$submenu){
if ($menu->idcategory == $submenu->idcategory){
if ($key > 0){
echo "</li>";
}
echo "<ul class=\"sub-menu\"><a href=\"category/".$submenu->urlsubcategory."\">".$submenu->namesubcategory."</a><li>";
}
}
}
?>
单个菜单在循环上效果很好,但是当菜单有子菜单时,循环在结构上变得错误。
ul
li-a--Single Menu--/a-/li ->Have no SubMenu, Works Good
li-a--Single Menu--/a-/li ->Have no SubMenu, Works Good
li-a--Single Menu--/a-/li ->Have SubMenu, False Structure
ul-class=submenu
a-Sub Menu-/a
li--/li
ul-class=submenu
a-Sub Menu-/a
li--/li
/ul
ul
菜单结构应该是这样的:
ul
li-a--Single Menu--/a-/li
li-a--Single Menu--/a-/li
li-a-Single Menu With Sub Menu-/a-/li
ul-class=submenu
li-a-Sub Menu-/a-/li
li-a-Sub Menu-/a-/li
li-a-Sub Menu-/a-/li
/ul
li-a--Single Menu--/a-/li
li-a--Single Menu--/a-/li
ul