首页  >  文章  >  后端开发  >  php生成无限栏目树

php生成无限栏目树

迷茫
迷茫原创
2017-03-26 10:17:583113浏览

栏目数组:

$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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn