服务报价 | 域名主机 | 网络营销 | 软件工具| [加入收藏]
 热线电话: #
当前位置: 主页 > php教程 > php教程 >

php递归用法与递归目录实例

时间:2016-04-27 13:08来源: 作者: 点击:
在php中递归算法是我们比得不多的一种数据遍历方式了,下面我来给大家介绍一下利用递归来做一下用的东西吧,看一个简单的递归实例. 例1,代码如下: function demo( $a ){ static $sum =1; if ( $

在php中递归算法是我们比得不多的一种数据遍历方式了,下面我来给大家介绍一下利用递归来做一下用的东西吧,看一个简单的递归实例.

例1,代码如下:

  1. function demo($a) {  
  2.  
  3.     static $sum=1;  
  4.  
  5.     if($a > 1){  
  6.  
  7.         $sum*=$a;  
  8.  
  9.         demo(--$a);  
  10.  
  11.     }else{  
  12.  
  13.         $a=$sum;  
  14.  
  15.         }  
  16.  
  17.         return $sum;  
  18.  
  19. echo demo(10); 

例2,遍历目录,代码如下:

  1. <?php 
  2. class listdir{ 
  3. var $depth
  4. var $dirname
  5. var $list
  6. var $tostring
  7.  
  8. function listdir($dir){ 
  9. $this->dirname=$dir
  10. $this->depth=0; 
  11. $this->tostring=”"; 
  12.  
  13. //把结果保存进多维数组 
  14. function getlist($dir=”"){ 
  15. if($dir==”")$dir=$this->dirname; 
  16. $d=@dir($dir); 
  17. while(false!==($item=$d->read())) 
  18. if($item!=”.”&&$item!=”..”) 
  19. $path=$dir.”/”.$item
  20. if(is_dir($path)){ 
  21. $this->depth+=1; 
  22. $this->getlist($path); 
  23. }else
  24. $this->list[$this->depth][]=$item
  25. $this->list[$this->depth]['directory']=$dir
  26. $this->depth-=1; 
  27. $d->close(); 
  28. return $this->list; 
  29.  
  30. //字符窜化结果 
  31.  
  32. function tostring($dir=”"){ 
  33. if($dir==”")$dir=$this->dirname; 
  34. $d=@dir($dir); 
  35. $this->tostring.=”<UL>n”; 
  36. $this->tostring.=”Directory:”.$dir.”n”; 
  37. while(false!==($item=$d->read())) 
  38. if($item!=”.”&&$item!=”..”) 
  39. $path=$dir.”/”.$item
  40. if(is_dir($path)){ 
  41. $this->depth+=1; 
  42. $this->tostring($path); 
  43. }else
  44. $this->tostring.=”<LI>”.$item.”</LI>n”; 
  45. $this->depth-=1; 
  46. $d->close(); 
  47. $this->tostring.=”</UL>n”; 
  48. return $this->tostring; 
  49. $wapdir=”jquery”; 
  50. $d=new listdir($wapdir); 
  51. echo $d->tostring(); 
  52. ?> 
  53. /* 
  54. 输出结果: 
  55. <UL> 
  56. Directory:jquery 
  57. <LI>jquery-1.3.2.js</LI> 
  58. <LI>jquery-1.3.2.min.js</LI> 
  59. <LI>jquery-1.3.2-vsdoc2.js</LI> 
  60. <LI>test.html</LI> 
  61. <LI>common.js</LI> 
  62. <UL> 
  63. Directory:jquery/d 
  64. <LI>common.js</LI> 
  65. <LI>jquery-1.3.2.js</LI> 
  66. </UL> 
  67. </UL> 
  68. */ 
(责任编辑:最模板)
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------