当你学习php无限极分类的时候,大家都觉得一个字“难”我也觉得很难,所以,现在都还在看,因为工作要用到,所以,就必须得研究研究。
到网上一搜php无限极分类,很多,但好多都是一个,并且,写的很乱,代码很多,让我们怎么学习嘛,那些都不靠谱,还是自己捣鼓捣鼓无限极分类了。
比如一个category表:有id, name, pid, sort 就这四个简单的字段,不要太复杂了。
id name pid sort
1 PHP 0 1
2 Javascript 0 2
3 MySQL 0 3
4 php类 1 1
5 smarty 1 2
6 私有方法 4 1
7 jQuery 2 1
我们需要一个二维数组的数据格式,然后传到sortCate()方法里,默认传一个参数$cate就可以了
$arr=array(
1=>array(‘id‘=>1,‘name‘=>‘PHP‘,‘pid‘=>0,‘sort‘=>1),
2=>array(‘id‘=>2,‘name‘=>‘Javascript‘,‘pid‘=>0,‘sort‘=>2),
3=>array(‘id‘=>3,‘name‘=>‘MySQL‘,‘pid‘=>0,‘sort‘=>3),
4=>array(‘id‘=>4,‘name‘=>‘php类‘,‘pid‘=>1,‘sort‘=>1),
5=>array(‘id‘=>5,‘name‘=>‘smarty‘,‘pid‘=>1,‘sort‘=>2),
6=>array(‘id‘=>6,‘name‘=>‘私有方法‘,‘pid‘=>4,‘sort‘=>1),
7=>array(‘id‘=>7,‘name‘=>‘jQuery‘,‘pid‘=>2,‘sort‘=>1),
);
//无限极分类方法一
static public function sortCate($cate,$pid=0,$level=0,$html=‘--‘){
$tree = array();
foreach($cate as $v){
if($v[‘pid‘] == $pid){
$v[‘level‘] = $level + 1;
$v[‘html‘] = str_repeat($html, $level);
$tree[] = $v;
$tree = array_merge($tree, self::sortOut($cate,$v[‘id‘],$level+1,$html));
}
}
return $tree;
}
}
//无限极分类方法二
function tree(&$list,$pid=0,$level=0,$html=‘--‘){
static $tree = array();
foreach($list as $v){
if($v[‘pid‘] == $pid){
$v[‘sort‘] = $level;
$v[‘html‘] = str_repeat($html,$level);
$tree[] = $v;
tree($list,$v[‘id‘],$level+1);
}
}
return $tree;
}
//无限极分类只带基本参数
public function tree($array,$pid=0){
$arr = array();
foreach($array as $v)
if($v[‘pid‘]==$pid){
$arr[] = $v;
$arr = array_merge($arr,self::tree($array,$v[‘id‘]));
}
}
return $arr;
}
PHP无限极分类
原文:http://www.cnblogs.com/xieweiseo/p/5182999.html