php生成无限栏目树

2018-06-22 05:11:58来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

栏目数组:
$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('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),

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

$tree = formatTree( $arr,0,1, $field = array('pid'=>'pid','id'=>'cid','children'=>'children') );
echo '<pre>';
print_r( $tree);

?>

  

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:php Stream Contexts 小记

下一篇:跟兄弟连学PHP之day1