1. 程式人生 > >PHP生成無限級選單樹

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']);
        }
    }
?>