联系电话:0755-27515592
最新动态:

PHP教程

你的位置: 首页>>智慧亿恩>>PHP教程

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

点击数:11312015-07-29 17:58:02 来源: 外贸网站建设,深圳外贸网站建设,深圳网站建设,外贸商城网站制作-亿恩科技

新闻摘要:在php中递归算法是我们比得不多的一种数据遍历方式了,下面我来给大家介绍一下利用递归来做一下用的东西吧,看一个简单的递归实例. 例1,代码如下: function demo( $a ){ static $sum =1; if ( $

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

例1,代码如下:

  1. function demo($a) { 
  2.     static $sum=1; 
  3.     if($a > 1){ 
  4.         $sum*=$a
  5.         demo(--$a); 
  6.     }else
  7.         $a=$sum
  8.         } 
  9.         return $sum
  10. }
  11. echo demo(10);

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

  1. <?php
  2. class listdir{
  3. var $depth;
  4. var $dirname;
  5. var $list;
  6. var $tostring;
  7. function listdir($dir){
  8. $this->dirname=$dir;
  9. $this->depth=0;
  10. $this->tostring=”";
  11. }
  12. //把结果保存进多维数组
  13. function getlist($dir=”"){
  14. if($dir==”")$dir=$this->dirname;
  15. $d=@dir($dir);
  16. while(false!==($item=$d->read()))
  17. {
  18. if($item!=”.”&&$item!=”..”)
  19. {
  20. $path=$dir.”/”.$item;
  21. if(is_dir($path)){
  22. $this->depth+=1;
  23. $this->getlist($path);
  24. }else{
  25. $this->list[$this->depth][]=$item;
  26. }
  27. }
  28. }
  29. $this->list[$this->depth]['directory']=$dir;
  30. $this->depth-=1;
  31. $d->close();
  32. return $this->list;
  33. }
  34. //字符窜化结果
  35. function tostring($dir=”"){
  36. if($dir==”")$dir=$this->dirname;
  37. $d=@dir($dir);
  38. $this->tostring.=”<UL>n”;
  39. $this->tostring.=”Directory:”.$dir.”n”;
  40. while(false!==($item=$d->read()))
  41. {
  42. if($item!=”.”&&$item!=”..”)
  43. {
  44. $path=$dir.”/”.$item;
  45. if(is_dir($path)){
  46. $this->depth+=1;
  47. $this->tostring($path);
  48. }else{
  49. $this->tostring.=”<LI>”.$item.”</LI>n”;
  50. }
  51. }
  52. }
  53. $this->depth-=1;
  54. $d->close();
  55. $this->tostring.=”</UL>n”;
  56. return $this->tostring;
  57. }
  58. }
  59. $wapdir=”jquery”;
  60. $d=new listdir($wapdir);
  61. echo $d->tostring();
  62. ?>
  63. /*
  64. 输出结果:
  65. <UL>
  66. Directory:jquery
  67. <LI>jquery-1.3.2.js</LI>
  68. <LI>jquery-1.3.2.min.js</LI>
  69. <LI>jquery-1.3.2-vsdoc2.js</LI>
  70. <LI>test.html</LI>
  71. <LI>common.js</LI>
  72. <UL>
  73. Directory:jquery/d
  74. <LI>common.js</LI>
  75. <LI>jquery-1.3.2.js</LI>
  76. </UL>
  77. </UL>
  78. */
【责任编辑:(Top) 返回页面顶端
贴心
全国7×24小时客服热线
安全
病毒杀除率高于99%
稳定
网站可用性高于99.9%
实力
服务68家上市企业及集团公司
亿恩科技手机站
关注亿恩科技微信

亿恩科技—企业信息化一站式服务专家


Copyright © 2008- 深圳市亿恩科技有限公司版权所有 粤ICP备15056041号

联系我们 | 常见问题 | 在线留言 | 支付方式 | 软件开发 | 我的观点 | 资质荣誉 | 服务流程