最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

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

时间:2014-07-12 11:31来源:未知 作者:最模板zuimoban 点击: 次
在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. } 
  20. 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. //把结果保存进多维数组 
  15. function getlist($dir=”"){ 
  16. if($dir==”")$dir=$this->dirname; 
  17. $d=@dir($dir); 
  18. while(false!==($item=$d->read())) 
  19. { 
  20. if($item!=”.”&&$item!=”..”) 
  21. { 
  22. $path=$dir.”/”.$item; 
  23. if(is_dir($path)){ 
  24. $this->depth+=1; 
  25. $this->getlist($path); 
  26. }else{ 
  27. $this->list[$this->depth][]=$item; 
  28. } 
  29. } 
  30. } 
  31. $this->list[$this->depth]['directory']=$dir; 
  32. $this->depth-=1; 
  33. $d->close(); 
  34. return $this->list; 
  35. } 
  36.  
  37. //字符窜化结果 
  38.  
  39. function tostring($dir=”"){ 
  40. if($dir==”")$dir=$this->dirname; 
  41. $d=@dir($dir); 
  42. $this->tostring.=”<UL>n”; 
  43. $this->tostring.=”Directory:”.$dir.”n”; 
  44. while(false!==($item=$d->read())) 
  45. { 
  46. if($item!=”.”&&$item!=”..”) 
  47. { 
  48. $path=$dir.”/”.$item; 
  49. if(is_dir($path)){ 
  50. $this->depth+=1; 
  51. $this->tostring($path); 
  52. }else{ 
  53. $this->tostring.=”<LI>”.$item.”</LI>n”; 
  54. } 
  55. } 
  56. } 
  57. $this->depth-=1; 
  58. $d->close(); 
  59. $this->tostring.=”</UL>n”; 
  60. return $this->tostring; 
  61. } 
  62. } 
  63. $wapdir=”jquery”; 
  64. $d=new listdir($wapdir); 
  65. echo $d->tostring(); 
  66. ?> 
  67. /* 
  68. 输出结果: 
  69. <UL> 
  70. Directory:jquery 
  71. <LI>jquery-1.3.2.js</LI> 
  72. <LI>jquery-1.3.2.min.js</LI> 
  73. <LI>jquery-1.3.2-vsdoc2.js</LI> 
  74. <LI>test.html</LI> 
  75. <LI>common.js</LI> 
  76. <UL> 
  77. Directory:jquery/d 
  78. <LI>common.js</LI> 
  79. <LI>jquery-1.3.2.js</LI> 
  80. </UL> 
  81. </UL> 
  82. */ 
(责任编辑:最模板)
------分隔线----------------------------
栏目列表
推荐内容