欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php生成无限栏目树

程序员文章站 2024-03-08 09:36:18
栏目数组: $arr=array( array('cid' => 2,'cname' => '新闻','pid' => 0), ar...

栏目数组:

$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); 
?> 

我们有两个方法来进行软件设计:一个是让其足够的简单以至于让bug无法藏身;另一个就是让其足够的复杂,让人找不到bug。前者更难一些。

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!