php语言

php两种无限分类方法实例

时间:2024-06-15 19:49:58 php语言 我要投稿
  • 相关推荐

php两种无限分类方法实例

  本文给出了递归方法和非递归方法实现的无限分类实例,有需要的朋友可以参考一下,希望对大家有所帮助!想了解更多相关信息请持续关注我们应届毕业生考试网!

  一、递归方法

  复制代码 代码如下:

  $items = array(

  array('id'=>1,'pid'=>0,'name'=>'一级11'),

  array('id'=>2,'pid'=>0,'name'=>'一级12'),

  array('id'=>3,'pid'=>1,'name'=>'二级21'),

  array('id'=>4,'pid'=>3,'name'=>'三级31'),

  array('id'=>5,'pid'=>1,'name'=>'二级22'),

  array('id'=>6,'pid'=>3,'name'=>'三级32'),

  array('id'=>7,'pid'=>6,'name'=>'四级41'),

  );

  $i = 0;

  function formatTree($arr, $pid = 0){

  $tree = array();

  $temp = array();

  global $i;

  if($arr){

  foreach($arr as $k=>$v){

  if($v['pid'] == $pid){//

  $temp = formatTree($arr, $v['id']);

  $temp && $v['son'] = $temp;

  $tree[] = $v;

  }

  }

  }

  return $tree;

  }

  print_r(formatTree($items));

  二、非递归方法

  复制代码 代码如下:

  function genTree($items) {

  $tree = array(); //格式化好的树

  foreach ($items as $item)

  if (isset($items[$item['pid']])){

  $items[$item['pid']]['son'][] = &$items[$item['id']];

  }

  else{

  $tree[] = &$items[$item['id']];

  }

  return $tree;

  }

  $items = array(

  1 => array('id' => 1, 'pid' => 0, 'name' => '一级11'),

  2 => array('id' => 2, 'pid' => 1, 'name' => '二级21'),

  3 => array('id' => 3, 'pid' => 1, 'name' => '二级23'),

  4 => array('id' => 4, 'pid' => 9, 'name' => '三级31'),

  5 => array('id' => 5, 'pid' => 4, 'name' => '四级43'),

  6 => array('id' => 6, 'pid' => 9, 'name' => '三级32'),

  7 => array('id' => 7, 'pid' => 4, 'name' => '四级41'),

  8 => array('id' => 8, 'pid' => 4, 'name' => '四级42'),

  9 => array('id' => 9, 'pid' => 1, 'name' => '二级25'),

  10 => array('id' => 10, 'pid' => 11, 'name' => '二级22'),

  11 => array('id' => 11, 'pid' => 0, 'name' => '一级12'),

  12 => array('id' => 12, 'pid' => 11, 'name' => '二级24'),

  13 => array('id' => 13, 'pid' => 4, 'name' => '四级44'),

  14 => array('id' => 14, 'pid' => 1, 'name' => '二级26'),

  15 => array('id' => 15, 'pid' => 8, 'name' => '五级51'),

  16 => array('id' => 16, 'pid' => 8, 'name' => '五级52'),

  17 => array('id' => 17, 'pid' => 8, 'name' => '五级53'),

  18 => array('id' => 18, 'pid' => 16, 'name' => '六级64'),

  );

  print_r(genTree($items));

【php两种无限分类方法实例】相关文章:

php实现伪静态的方法实例09-25

php画图实例07-16

php生成缩略图的两种方法05-24

PHP实用的代码实例08-12

php查询mysql的实例09-09

PHP socket的配置及实例10-16

php生成缩略图的两种方法(代码)08-08

php简单伪静态实例09-16

php使用GeoIP库实例08-09

php:树形结构的算法实例10-18