首页 > 后端开发 > php教程 > php生成无限栏目树

php生成无限栏目树

迷茫
发布: 2023-03-06 22:22:02
原创
3165 人浏览过

栏目数组:

$arr=Array(
    Array('cid' => 2,'cname' => '新闻','pid' => 0),
    Array('cid' => 4,'cname' =>'体育','pid' => 0),
    Array('cid' => 5,'cname' => '娱乐','pid' => 0),
    Array('cid' => 7,'cname' => '热点新闻','pid' =>2),
    Array('cid' => 8,'cname' => '小众新闻','pid' => 2),
    Array('cid' => 9,'cname' => '民谣新闻','pid' => 8),
);
登录后复制
<?php
$arr=Array(
    Array(&#39;cid&#39; => 2,&#39;cname&#39; => &#39;新闻&#39;,&#39;pid&#39; => 0),
    Array(&#39;cid&#39; => 4,&#39;cname&#39; =>&#39;体育&#39;,&#39;pid&#39; => 0),
    Array(&#39;cid&#39; => 5,&#39;cname&#39; => &#39;娱乐&#39;,&#39;pid&#39; => 0),
    Array(&#39;cid&#39; => 7,&#39;cname&#39; => &#39;热点新闻&#39;,&#39;pid&#39; =>2),
    Array(&#39;cid&#39; => 8,&#39;cname&#39; => &#39;小众新闻&#39;,&#39;pid&#39; => 2),
    Array(&#39;cid&#39; => 9,&#39;cname&#39; => &#39;民谣新闻&#39;,&#39;pid&#39; => 8),

);
function formatTree($array, $pid = 0,$level = 1,$field = array(&#39;pid&#39;=>&#39;pid&#39;,&#39;id&#39;=>&#39;id&#39;,&#39;children&#39;=>&#39;children&#39;)){
        $arr = array();
        foreach ($array as &$v) {
            if ($v[$field[&#39;pid&#39;]] == $pid) {
                $v[&#39;level&#39;] = $level;
                $tem = formatTree($array, $v[$field[&#39;id&#39;]],$v[&#39;level&#39;]+1,$field);
                //判断是否存在子数组
                $tem && $v[$field[&#39;children&#39;]] = $tem;
                $arr[] = $v;
            }
        }
        return $arr;
    }

$tree = formatTree( $arr,0,1, $field = array(&#39;pid&#39;=>&#39;pid&#39;,&#39;id&#39;=>&#39;cid&#39;,&#39;children&#39;=>&#39;children&#39;) );
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r( $tree);

?>
登录后复制

以上是php生成无限栏目树 的详细内容。更多信息请关注PHP中文网其他相关文章!

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