共计 1759 个字符,预计需要花费 5 分钟才能阅读完成。
这篇文章次要介绍了 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));