首页 > php教程 > php手册 > 正文

php递归方法实现无限分类实例

WBOY
发布: 2016-05-25 16:45:07
原创
906 人浏览过

数组代码如下:

<?php
$items = array(
    array(
        &#39;id&#39; => 1,
        &#39;pid&#39; => 0,
        &#39;name&#39; => &#39;一级11&#39;
    ) ,
    array(
        &#39;id&#39; => 11,
        &#39;pid&#39; => 0,
        &#39;name&#39; => &#39;一级12&#39;
    ) ,
    array(
        &#39;id&#39; => 2,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;二级21&#39;
    ) ,
    array(
        &#39;id&#39; => 10,
        &#39;pid&#39; => 11,
        &#39;name&#39; => &#39;二级22&#39;
    ) ,
    array(
        &#39;id&#39; => 3,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;二级23&#39;
    ) ,
    array(
        &#39;id&#39; => 12,
        &#39;pid&#39; => 11,
        &#39;name&#39; => &#39;二级24&#39;
    ) ,
    array(
        &#39;id&#39; => 13,
        &#39;pid&#39; => 12,
        &#39;name&#39; => &#39;三级31&#39;
    ) ,
    array(
        &#39;id&#39; => 9,
        &#39;pid&#39; => 1,
        &#39;name&#39; => &#39;二级25&#39;
    ) ,
);
?>
登录后复制

函数代码如下:

<?php
function formatTree($array, $pid = 0) {
    $arr = array();
    $tem = array();
    foreach ($array as $v) {
        if ($v[&#39;pid&#39;] == $pid) {
            $tem = formatTree($array, $v[&#39;id&#39;]);
            //判断是否存在子数组
            $tem && $v[&#39;son&#39;] = $tem;
            $arr[] = $v;
        }
    }
    return $arr;
}
?>
登录后复制

其中,数组一定要包含id和pid用以指定数组值之间的层级关系.


文章链接:

随便收藏,请保留本文地址!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板