前端之家收集整理的这篇文章主要介绍了
php生成无限栏目树,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_0@
栏目数组:
<div class="jb51code">
<pre class="brush:php;">
$arr=Array(
Array('cid' => 2,'cname' => '新闻','pid' => 0),Array('cid' => 4,'cname' =>'体育',Array('cid' => 5,'cname' => '娱乐',Array('cid' => 7,'cname' => '热点新闻','pid' =>2),Array('cid' => 8,'cname' => '小众新闻','pid' => 2),Array('cid' => 9,'cname' => '民谣新闻','pid' => 8),);
PHP;">
2,);
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,1,'id'=>'cid','children'=>'children') );
echo '
';
print_r( $tree);
?>