php用递归方法实现无限级分类

大家讲道理
Libérer: 2023-03-05 18:10:02
original
2275 Les gens l'ont consulté

相信很多小伙伴们在学PHP的时候都会想制作一个网站来提高自己的技术,像是企业网站,商城网站这种他们个最近的功能,栏目的管理,用到的都是无限级分类的方法,我们接下来就会通过对无限级分类技术的学习来探究其深层的实现逻辑。

 什么是无限级分类?

无限级分类是一种分类技巧,例如部门组织,文章分类,学科分类等常用到无限级分类,将其简单理解成分类就好了。其实我们仔细想一下,生活中的分类简直太多了,衣服可以分为男装和女装,也可以分为上衣和裤子,也可以根据年龄段分类。分类无处不在,分类显得“无限”。我这里就不说无限分类的必要性了。

无限级分类原理简介

无限分类看似"高大上",实际上原理是非常简单的 。无限分类不仅仅需要代码的巧妙性,也要依托数据库设计的合理性。要满足无限级分类,数据库需要有两个必须的字段,id,pid。id用来标识自身,而pid则是用来表明父级id。也就是说,每个分类记录不仅描述了自身,还描述了与其关心最为紧密的另一个id。看似复杂的事情被这样一个小技巧解决了。

实例

建库

表名:category

id int 主键,自增

name varchar 分类名称

pid int 父类id,默认0

顶级分类的 pid 默认就是0了。当我们想取出某个分类的子分类树的时候,基本思路就是递归,当然,出于效率问题不建议每次递归都查询数据库,通常的做法是先讲所有分类取出来,保存到PHP数组里,再进行处理,最后还可以将结果缓存起来以提高下次请求的效率。
先来构建一个原始数组,这个直接从数据库中拉出来就行:

$categories = array( array('id'=>1,'name'=>'电脑','pid'=>0), array('id'=>2,'name'=>'手机','pid'=>0), array('id'=>3,'name'=>'笔记本','pid'=>1), array('id'=>4,'name'=>'台式机','pid'=>1), array('id'=>5,'name'=>'智能机','pid'=>2), array('id'=>6,'name'=>'功能机','pid'=>2), array('id'=>7,'name'=>'超级本','pid'=>3), array('id'=>8,'name'=>'游戏本','pid'=>3), )
Copier après la connexion

目标是将它转化为下面这种结构
电脑 —笔记本 ——-超级本 ——-游戏本 —台式机 手机 —智能机 —功能机
用数组来表示的话,可以增加一个 children 键来存储它的子分类:

array( //1对应id,方便直接读取 1 => array( 'id'=>1, 'name'=>'电脑', 'pid'=>0, children=>array( &array( 'id'=>3, 'name'=>'笔记本', 'pid'=>1, 'children'=>array( //此处省略 ) ), &array( 'id'=>4, 'name'=>'台式机', 'pid'=>1, 'children'=>array( //此处省略 ) ), ) ), //其他分类省略 )
Copier après la connexion

处理过程:

$tree = array(); //第一步,将分类id作为数组key,并创建children单元 foreach($categories as $category){ $tree[$category['id']] = $category; $tree[$category['id']]['children'] = array(); } //第二部,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。 foreach ($tree as $k=>$item) { if ($item['pid'] != 0) { $tree[$item['pid']]['children'][] = &$tree[$k]; } } print_r($tree);
Copier après la connexion

打印结果如下:

Array( [1] => Array ( [id] => 1 [name] => 电脑 [pid] => 0 [children] => Array ( [0] => Array ( [id] => 3 [name] => 笔记本 [pid] => 1 [children] => Array ( [0] => Array ( [id] => 7 [name] => 超级本 [pid] => 3 [children] => Array ( ) ) [1] => Array ( [id] => 8 [name] => 游戏本 [pid] => 3 [children] => Array ( ) ) ) ) [1] => Array ( [id] => 4 [name] => 台式机 [pid] => 1 [children] => Array ( ) ) ) ) [2] => Array ( [id] => 2 [name] => 手机 [pid] => 0 [children] => Array ( [0] => Array ( [id] => 5 [name] => 智能机 [pid] => 2 [children] => Array ( ) ) [1] => Array ( [id] => 6 [name] => 功能机 [pid] => 2 [children] => Array ( ) ) ) ) [3] => Array ( [id] => 3 [name] => 笔记本 [pid] => 1 [children] => Array ( [0] => Array ( [id] => 7 [name] => 超级本 [pid] => 3 [children] => Array ( ) ) [1] => Array ( [id] => 8 [name] => 游戏本 [pid] => 3 [children] => Array ( ) ) ) ) [4] => Array ( [id] => 4 [name] => 台式机 [pid] => 1 [children] => Array ( ) ) [5] => Array ( [id] => 5 [name] => 智能机 [pid] => 2 [children] => Array ( ) ) [6] => Array ( [id] => 6 [name] => 功能机 [pid] => 2 [children] => Array ( ) ) [7] => Array ( [id] => 7 [name] => 超级本 [pid] => 3 [children] => Array ( ) ) [8] => Array ( [id] => 8 [name] => 游戏本 [pid] => 3 [children] => Array ( ) ) )
Copier après la connexion

优点:关系清楚,修改上下级关系简单。

缺点:使用PHP处理,如果分类数量庞大,效率也会降低。


引申-------递归函数

递归函数是我们常用到的一类函数,最基本的特点是函数自身调用自身,但必须在调用自身前有条件判断,否则无限无限调用下去。实现递归函数可以采取什么方式呢?本文列出了三种基本方式。理解其原来需要一定的基础知识水品,包括对全局变量,引用,静态变量的理解,也需对他们的作用范围有所理解。递归函数也是解决无限级分类的一个很好地技巧。如果对无限级分类感兴趣,请参照php利用递归函数实现无限级分类。我习惯套用通俗的话解释复杂的道理,您确实不明白请参见手册。

利用引用做参数

  先不管引用做不做参数,必须先明白引用到底是什么?引用不过是指两个不同名的变量指向同一块存储地址。本来每个变量有各自的存储地址,赋值删除各行其道。现在可好,两个变量共享一块存储地址。 $a=&$b; 。实际上指的是 $a 不管不顾自己原来的存储地址,非要和 $b 共享一室了。因而任何对存储地址数值的改变都会影响两个值。  

  函数之间本来也是各行其是,即便是同名函数。递归函数是考虑将引用作为参数,成为一个桥梁,形成两个函数间的数据共享。虽然两个函数见貌似操作的是不同地址,但是实际上操作的是一块儿内存地址。

function test($a=0,&$result=array()){ $a++; if ($a<10) { $result[]=$a; test($a,$result); } echo $a; return $result; }
Copier après la connexion


  上面的例子非常简答,以a<10作为判断条件,条件成立,则把a<10作为判断条件,条件成立,则把a赋给result[];将result[];将result的引用传入函数,会将每一次递归产生的a添加到结果数组a添加到结果数组result。因而本例生成的$result数组是 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 ) 。

本例比较有意思的是echo a的值。相信很多人认为是12345678910吧,其实不然,是1098765432。为什么呢?因为函数还没执行echoa的值。相信很多人认为是12345678910吧,其实不然,是1098765432。为什么呢?因为函数还没执行echoa前就进行了下一次的函数递归。真正执行echo a是当a是当a<10条件不满足的时候,echo a,返回a,返回result,对于上一层而言,执行完递归函数,开始执行本层的echo $a,依次类推。

  利用全局变量

  利用全局变量完成递归函数,请确保你确实理解什么是全局变量。global在函数内申明变量不过是外部变量的同名引用。变量的作用范围仍然在本函数范围内。改变这些变量的值,外部同名变量的值自然也改变了。但一旦用了&,同名变量不再是同名引用。利用全局变量实现递归函数没必要理解到这么深的一层,还保持原有对全局变量的看法就可以顺理成章理解递归函数。

function test($a=0,$result=array()){ global $result; $a++; if ($a<10) { $result[]=$a; test($a,$result); } return $result; }
Copier après la connexion


  利用静态变量

  我们常常在类中见到static,今天我们把它利用到递归函数中。请记住static的作用:仅在第一次调用函数的时候对变量进行初始化,并且保留变量值。

例子:

function test(){ static $count=0; echo $count; $count++; } test(); test(); test(); test(); test();
Copier après la connexion


  请问这一段代码的执行结果是多少?是00000么?必然不是。是01234。首先第一次调用test(),static对 $count 进行初始化,其后每一次执行完都会保留 $count 的值,不再进行初始化,相当于直接忽略了 static$count=0; 这一句。

  因而将static应用到递归函数作用可想而知。在将需要作为递归函数间作为“桥梁"的变量利用static进行初始化,每一次递归都会保留"桥梁变量"的值。

function test($a=0){ static $result=array(); $a++; if ($a<10) { $result[]=$a; test($a); } return $result; }
Copier après la connexion

  总结

  所谓递归函数,重点是如何处理函数调用自身是如何保证所需要的结果得以在函数间合理"传递",当然也有不需要函数之间传值得递归函数,例如:

function test($a=0){ $a++; if ($a<10) { echo $a; test($a); } }
Copier après la connexion

面对这样的函数,深入理解变量引用相关知识对解决这类问题大有裨益。

相关文章:

php递归实现无限级分类树

揭露php无限级分类的原理

php无限级分类实现方法分析

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!