PHP生成无限级菜单树
俗话说:程序猿会一门语言,再学其他的也会很快,
一个学Java的,让做PHP,这里就记录一下PHP生成菜单树,实现分层,
原理:递归,
语音:PHP
数据格式:没有树结构化的数组,例如:
Array
(
[0] => Array
(
[CategoryID] => 1
[CategoryLayer] => 1
[ShortCHNName] => 一级菜单1
[ParentID] => 0
[ImageURL] => icons/6.gif
)
[1] => Array
(
[CategoryID] => 2
[CategoryLayer] => 1
[ShortCHNName] => 一级菜单2
[ParentID] => 0
[ImageURL] => icons/6.gif
)
[3] => Array
(
[CategoryID] => 3
[CategoryLayer] => 2
[ShortCHNName] => 【一级菜单1】的二级菜单
[ParentID] => 1
[ImageURL] => icons/3.gif
)
...
源码贴上,供参考用
<?php
function getTreeChildren($catelist,$pid){
$html = "";
foreach ($catelist as $item){
if($item['ParentID'] == $pid){
$html .= '<li>'.$item['ShortCHNName'];
$html .= getTreeChildren($catelist,$item['CategoryID']);
$html .= '</li>';
}
}
return $html ? '<ul>' .$html. '</ul>' : $html;
}
foreach ($catelist as $cate){
$hrefurl = Yii::app()->createUrl("tipexn/dataservice", ["cid" => $cate["CategoryID"]]);
$imgurl = Yii::app()->params["ctx"].$cate["ImageURL"];
$shortName = $cate['ShortCHNName'];
if($cate['CategoryLayer'] == 1){
echo '<div class="contentist">';
echo ' <div class="contentist_div">';
echo ' <a href="'.$hrefurl.'" title=""> ';
echo ' <div class="left_menu_div_img">';
echo ' <img class="left_menu_img" src="'.$imgurl.'"/>';
echo ' </div>';
echo ' <div class="content_left_span">'.$shortName.'</div>';
echo ' </a>';
echo ' </div>';
echo ' </div>';
echo'<div class="separator_menu" ></div>';
echo getTreeChildren($catelist,$cate['CategoryID']);
}
}
?>