萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php兩種無限分類方法實例

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

copyright © 萬盛學電腦網 all rights reserved