最新赞助活动温馨提示:自愿赞助服务器费用,学生和没有工作的整站资源免费下载!
头像

php生成无限栏目树示例代码

来源:http://erdangjiade.com/topic/1752.html 你好,世界。 2017-09-25 22:42浏览(19)

如果网站采用了无限级栏目结构,我们可以将网站所有栏目获取出来组成一个树形结构。本文主要介绍了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),
);
<?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); 
?> 

以上就是php生成无限栏目树示例代码的详细内容,更多请关注二当家的素材网其它相关文章!

评论0
头像

友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群

1 2