| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx

用 PHP 实现无限分类的好方法

0
PHP HTML C/C++ Go 16680 次浏览

效果:

计算机操作系统
|-Linux 系统
|–Linux相关网站
|—Linuxpig.com
|—Linux.org
|-Windows 系统
开源
|-open-open.com

 

数据的存储结构是这样的:

id,pid,name

解释:

id为自身编号,pid为父分类的编号(如果根则为0),name 为分类名称

 

无限分类的思想:

也就是用一个数组来表示一个树形的结构的方法,基本思路是结果数组 tree 中,所有根元素放到 tree[0] 中。二级栏目(根元素的子)放到 tree[1] 中,第n层次的元素的子元素放到 tree[n] 当中。

 

具体实现:

1,"pid"=>0,"name"=>"计算机操作系统");
$array[] = array("id"=>2,"pid"=>0,"name"=>"探险");
$array[] = array("id"=>3,"pid"=>1,"name"=>"Linux 系统");
$array[] = array("id"=>4,"pid"=>1,"name"=>"Windows 系统");
$array[] = array("id"=>5,"pid"=>3,"name"=>"Linux相关网站");
$array[] = array("id"=>6,"pid"=>5,"name"=>"Linuxpig.com");
$array[] = array("id"=>7,"pid"=>5,"name"=>"Linux.org");
$array[] = array("id"=>8,"pid"=>2,"name"=>"52risk.com");

showCategory($array);

function showCategory($array){
    $tree = array();
    if( $array ){
        foreach ( $array as $v ){
            $pid = $v['pid'];
            $list = @$tree[$pid] ?$tree[$pid] : array();
            array_push( $list, $v );
            $tree[$pid] = $list;
        }
    }

    //遍历输出根分类
    foreach($tree[0] as $k=>$v)
    {
        echo "$v[name]
";
        //遍历输出根分类相应的子分类
        if($tree[$v['id']]) drawTree($tree[$v['id']],$tree,0);
        echo "
"; } } function drawTree($arr,$tree,$level) { $level++; $prefix = str_pad("|",$level+1,'-',STR_PAD_RIGHT); foreach($arr as $k2=>$v2) { echo "$prefix$v2[name] "; if(isset($tree[$v2['id']])) drawTree($tree[$v2['id']],$tree,$level); } } ?>
具体项目中可能样式和数据来源需要调整。

转自:http://www.linuxpig.com/2011/01/php-endless-category/

2个答案

0

You'll find that getting started is always the toughest part but once you get into a rhythm it won't take too long before all those compulsions just melt away--and you'll actually enjoy writing again. The essay writer online explains some tips that also might help you out.

0

php