本文实例讲述了PHP无限极分类函数的实现方法。分享给大家供大家参考,具体如下:
在开发程序的时候,有时候,我们需要获取所有栏目(包括一级栏目、二级栏目、三级栏目等等),并按照父子关系形成树型结构。可以采取使用递归或者通过引用方式(php中引用类似C或者C++中的指针,只不过换一种说法而已)。
通过引用方式实现无限极分类
思路:
1.即所有待处理的数据进行包装成下标为主键id(pk)的数组,便于有pid获取对应的父栏目。
2.对包装的数据进行循环,如果为根节点,则将其引用添加到tree中,否则,将其引用添加到其父类的子元素中。这样虽然tree中,只是添加了根节点,但是每个根节点如果有子元素,其中包含了子元素的引用。故能形成树型。
代码如下
/** * 把返回的数据集转换成Tree * @param array $list 要转换的数据集 * @param string $pk 自增字段(栏目id) * @param string $pid parent标记字段 * @return array * @author dqs <1696232133@qq.com> */function make_tree($list,$pk='id',$pid='pid',$child='_child',$root=0){ $tree=array(); $packData=array(); foreach ($list as $data) { $packData[$data[$pk]] = $data; } foreach ($packData as $key =>$val){ if($val[$pid]==$root){//代表跟节点 $tree[]=& $packData[$key]; }else{ //找到其父类 $packData[$val[$pid]][$child][]=& $packData[$key]; } } return $tree;}
数据结构如下:
执行结果如下
Array( [0] => Array ( [id] => 6 [pid] => 0 [title] => 测试1 [url] => test1 [sort] => 0 [create_time] => 1464076199 [update_time] => 1464076199 [status] => 1 [target] => 0 ) [1] => Array ( [id] => 7 [pid] => 0 [title] => 测试2 [url] => test2 [sort] => 0 [create_time] => 1464076218 [update_time] => 1464076218 [status] => 1 [target] => 0 ) [2] => Array ( [id] => 1 [pid] => 0 [title] => 首页 [url] => Index/index [sort] => 1 [create_time] => 1379475111 [update_time] => 1379923177 [status] => 1 [target] => 0 ) [3] => Array ( [id] => 2 [pid] => 0 [title] => 博客 [url] => Article/index?category=blog [sort] => 2 [create_time] => 1379475131 [update_time] => 1379483713 [status] => 1 [target] => 0 [_child] => Array ( [0] => Array ( [id] => 4 [pid] => 2 [title] => 个人博客 [url] => ownblog [sort] => 0 [create_time] => 1464075558 [update_time] => 1464075558 [status] => 1 [target] => 0 [_child] => Array ( [0] => Array ( [id] => 8 [pid] => 4 [title] => 新浪博客 [url] => sinaBlog [sort] => 0 [create_time] => 1464077276 [update_time] => 1464077276 [status] => 1 [target] => 0 ) ) ) [1] => Array ( [id] => 5 [pid] => 2 [title] => 他人博客 [url] => otherBlog [sort] => 0 [create_time] => 1464075582 [update_time] => 1464075582 [status] => 1 [target] => 0 ) ) ) [4] => Array ( [id] => 3 [pid] => 0 [title] => 官网 [url] => http://www.onethink.cn [sort] => 3 [create_time] => 1379475154 [update_time] => 1387163458 [status] => 1 [target] => 0 ))
新闻热点
疑难解答