Home > php教程 > php手册 > php中实现无限级分类的方法

php中实现无限级分类的方法

PHPz
Release: 2018-10-19 14:06:49
Original
1201 people have browsed it

这篇文章主要介绍了php实现无限级分类,方法非常的简单,代码也很难简洁,需要的朋友可以参考下

代码如下:

$area = array(
array('id'=>1,'name'=>'安徽','parent'=>0),
array('id'=>2,'name'=>'海淀','parent'=>7),
array('id'=>3,'name'=>'濉溪县','parent'=>5),
array('id'=>4,'name'=>'昌平','parent'=>7),
array('id'=>5,'name'=>'淮北','parent'=>1),
array('id'=>6,'name'=>'朝阳','parent'=>7),
array('id'=>7,'name'=>'北京','parent'=>0),
array('id'=>8,'name'=>'上地','parent'=>2)
);
Copy after login

1.递归,查找子孙树

代码如下:

function subtree($arr,$id=0,$lev=1) {
    $subs = array(); // 子孙数组
    foreach($arr as $v) {
        if($v['parent'] == $id) {
            $v['lev'] = $lev;
            $subs[] = $v; // 举例说找到array('id'=>1,'name'=>'安徽','parent'=>0),
            $subs = array_merge($subs,subtree($arr,$v['id'],$lev+1));
        }
    }
    return $subs;
}
$tree = subtree($area,0,1);
foreach($tree as $v) {
    echo str_repeat(&#39;  &#39;,$v[&#39;lev&#39;]),$v[&#39;name&#39;],&#39;<br />&#39;;
}
Copy after login

2.递归,求家谱树

家谱树的应用 ,如面包屑导航 首页 > 手机类型 > CDMA手机 > 公益PHP > 递归应用

代码如下:

function familytree($arr,$id) {
    $tree = array();
    foreach($arr as $v) {
        if($v[&#39;id&#39;] == $id) {// 判断要不要找父栏目
            if($v[&#39;parent&#39;] > 0) { // parnet>0,说明有父栏目
                $tree = array_merge($tree,familytree($arr,$v[&#39;parent&#39;]));
            }
            $tree[] = $v; // 以找到上地为例
        }
    }
    return $tree;
}
print_r(familytree($area,8)); // 北京->海淀->上地
Copy after login

2.迭代,求家谱树

代码如下:

// 迭代,效率比递归高,代码也没多.
// 找家谱树推荐用迭代
function tree($arr,$id) {
    $tree = array();
    while($id !== 0) {
        foreach($arr as $v) {
            if($v[&#39;id&#39;] == $id) {
                $tree[] = $v;
                $id = $v[&#39;parent&#39;];
                break;
            }    
        }
    }
    return $tree;
}
print_r(tree($area,8));
Copy after login

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template