在php中遞歸算法是我們比得不多的一種數(shù)據(jù)遍歷方式了,下面我來給大家介紹一下利用遞歸來做一下用的東西吧,看一個(gè)簡單的遞歸實(shí)例.
例1,代碼如下:
- function demo($a) {
- static $sum=1;
- if($a > 1){
- $sum*=$a;
- demo(--$a);
- }else{
- $a=$sum;
- }
- return $sum;
- }
- echo demo(10);
例2,遍歷目錄,代碼如下:
- <?php
- class listdir{
- var $depth;
- var $dirname;
- var $list;
- var $tostring;
- function listdir($dir){
- $this->dirname=$dir;
- $this->depth=0;
- $this->tostring=”";
- }
- //把結(jié)果保存進(jìn)多維數(shù)組
- function getlist($dir=”"){
- if($dir==”")$dir=$this->dirname;
- $d=@dir($dir);
- while(false!==($item=$d->read()))
- {
- if($item!=”.”&&$item!=”..”)
- {
- $path=$dir.”/”.$item;
- if(is_dir($path)){
- $this->depth+=1;
- $this->getlist($path);
- }else{
- $this->list[$this->depth][]=$item;
- }
- }
- }
- $this->list[$this->depth]['directory']=$dir;
- $this->depth-=1;
- $d->close();
- return $this->list;
- }
- //字符竄化結(jié)果
- function tostring($dir=”"){
- if($dir==”")$dir=$this->dirname;
- $d=@dir($dir);
- $this->tostring.=”<UL>n”;
- $this->tostring.=”Directory:”.$dir.”n”;
- while(false!==($item=$d->read()))
- {
- if($item!=”.”&&$item!=”..”)
- {
- $path=$dir.”/”.$item;
- if(is_dir($path)){
- $this->depth+=1;
- $this->tostring($path);
- }else{
- $this->tostring.=”<LI>”.$item.”</LI>n”;
- }
- }
- }
- $this->depth-=1;
- $d->close();
- $this->tostring.=”</UL>n”;
- return $this->tostring;
- }
- }
- $wapdir=”jquery”;
- $d=new listdir($wapdir);
- echo $d->tostring();
- ?>
- /*
- 輸出結(jié)果:
- <UL>
- Directory:jquery
- <LI>jquery-1.3.2.js</LI>
- <LI>jquery-1.3.2.min.js</LI>
- <LI>jquery-1.3.2-vsdoc2.js</LI>
- <LI>test.html</LI>
- <LI>common.js</LI>
- <UL>
- Directory:jquery/d
- <LI>common.js</LI>
- <LI>jquery-1.3.2.js</LI>
- </UL>
- </UL>
- */
新聞熱點(diǎn)
疑難解答