您好,欢迎访问一九零五行业门户网

php无限分类树[支持子分类排序]

没有人规定一定要使用类,你写成一个函数也可以,每个人的编程习惯、风格、喜好都不一样,关于封装成类是为了使这段程序具有结构条理性,而不是随意放置,关于类中包含的多个方法(vtree、htree)主要应对不同业务场景,vtree为单线纵向结构,而htree为树形结构。
classtree.class.php
<?php /** * 无限分类树(支持子分类排序) * version:1.4 * author:veris * website:www.mostclan.com */ class classtree { /** * 分类排序(降序) */ static public function sort($arr,$cols){ //子分类排序 foreach ($arr as $k => &$v) { if(!empty($v['sub'])){ $v['sub']=self::sort($v['sub'],$cols); } $sort[$k]=$v[$cols]; } if(isset($sort)) array_multisort($sort,sort_desc,$arr); return $arr; } /** * 横向分类树 */ static public function htree($arr,$pid=0){ foreach($arr as $k => $v){ if($v['pid']==$pid){ $data[$v['id']]=$v; $data[$v['id']]['sub']=self::htree($arr,$v['id']); } } return isset($data)?$data:array(); } /** * 纵向分类树 */ static public function vtree($arr,$pid=0){ foreach($arr as $k => $v){ if($v['pid']==$pid){ $data[$v['id']]=$v; $data+=self::vtree($arr,$v['id']); } } return isset($data)?$data:array(); } }
返回例子:
array ( [4] => array ( [id] => 4 [pid] => 0 [name] => 上海 [sort] => 2 ) [5] => array ( [id] => 5 [pid] => 4 [name] => 闵行 [sort] => 0 ) [1] => array ( [id] => 1 [pid] => 0 [name] => 浙江 [sort] => 0 ) [13] => array ( [id] => 13 [pid] => 1 [name] => 金华 [sort] => 1 ) [10] => array ( [id] => 10 [pid] => 1 [name] => 宁波 [sort] => 0 ) [6] => array ( [id] => 6 [pid] => 10 [name] => 宁海 [sort] => 0 ) ) array ( [4] => array ( [id] => 4 [pid] => 0 [name] => 上海 [sort] => 2 [sub] => array ( [5] => array ( [id] => 5 [pid] => 4 [name] => 闵行 [sort] => 0 [sub] => array ( ) ) ) ) [1] => array ( [id] => 1 [pid] => 0 [name] => 浙江 [sort] => 0 [sub] => array ( [13] => array ( [id] => 13 [pid] => 1 [name] => 金华 [sort] => 1 [sub] => array ( ) ) [10] => array ( [id] => 10 [pid] => 1 [name] => 宁波 [sort] => 0 [sub] => array ( [6] => array ( [id] => 6 [pid] => 10 [name] => 宁海 [sort] => 0 [sub] => array ( ) ) ) ) ) ) )
public function vtree($arr,$pid=0){ foreach($arr as $k => $v){ if($v['pid']==$pid){ $data[$v['id']]=$v; $data+=vtree($arr,$v['id']); } } return isset($data)?$data:array(); }
以上就是php无限分类树[支持子分类排序]的详细内容。
其它类似信息

推荐信息