实现无限极分类
首先先看一下数据结构
//数据结构
// $items = array(
// 1 => array('id' => 1, 'pid' => 0, 'name' => 'anhui'),
// 2 => array('id' => 2, 'pid' => 0, 'name' => 'zhejiang'),
// 3 => array('id' => 3, 'pid' => 1, 'name' => 'hefei'),
// 4 => array('id' => 4, 'pid' => 3, 'name' => 'zhangfeng'),
// 5 => array('id' => 5, 'pid' => 1, 'name' => 'anqing'),
// 6 => array('id' => 6, 'pid' => 0, 'name' => 'sichuan'),
// 7 => array('id' => 7, 'pid' => 0, 'name' => 'dayang'),
// 8 => array('id' => 8, 'pid' => 3, 'name' => 'guangdong'),
// );
//显示树结构
function generateTree($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;
}
//新增子分类
function addtree(&$arr,$pid,$name){
$num=count($arr)+1;
if($num==0){$num=0;}
$arr[$num]=array(
'id'=>$num,
'pid'=>$pid,
'name'=>$name
);
}
两个方法 addtree用来新增 genrateTree用来排序返回一个数组
以下附上完整代码
$num,
'pid'=>$pid,
'name'=>$name
);
}
$items=array();
//数据结构
// $items = array(
// 1 => array('id' => 1, 'pid' => 0, 'name' => 'anhui'),
// 2 => array('id' => 2, 'pid' => 0, 'name' => 'zhejiang'),
// 3 => array('id' => 3, 'pid' => 1, 'name' => 'hefei'),
// 4 => array('id' => 4, 'pid' => 3, 'name' => 'zhangfeng'),
// 5 => array('id' => 5, 'pid' => 1, 'name' => 'anqing'),
// 6 => array('id' => 6, 'pid' => 0, 'name' => 'sichuan'),
// 7 => array('id' => 7, 'pid' => 0, 'name' => 'dayang'),
// 8 => array('id' => 8, 'pid' => 3, 'name' => 'guangdong'),
// );
addtree($items,'0','成都');
addtree($items,'1','自贡');
addtree($items,'2','富顺');
addtree($items,'0','上海');
addtree($items,'4','外滩');
addtree($items,'3','市中花园');
addtree($items,'3','福州花园');
// showtree($items);
print_r(generateTree($items));
?>