Recursive algorithm in PHP is not much of our data traversal method, let me introduce you to the use of recursion to do something.
See a simple recursive instance
Example 1
The code is as follows |
Copy Code |
function Demo ($a) { static $sum = 1; if ($a > 1) { $sum *= $a; Demo (--$a); }else{ $a = $sum; } return $sum; }
Echo Demo (10); |
Example 2
Traverse Directory
The code is as follows |
Copy Code |
Class listdir{ var $depth; var $dirname; var $list; var $tostring; function Listdir ($dir) { $this->dirname= $dir; $this->depth=0; $this->tostring= ""; } Save the result in a multidimensional array 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; } Character channeling results function ToString ($dir = "") { if ($dir = = "") $dir = $this->dirname; $d = @dir ($dir); $this->tostring.= "
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.= "
- ". $item."
n ";
}
}
}
$this->depth-=1;
$d->close ();
$this->tostring.= "
n "; return $this->tostring; } } $wapdir = "jquery"; $d =new Listdir ($wapdir); echo $d->tostring (); ?>Output Result:
Directory:jquery
- Jquery-1.3.2.js
- Jquery-1.3.2.min.js
- Jquery-1.3.2-vsdoc2.js
- Test.html
- Common.js
directory:jquery/d
- Common.js
- Jquery-1.3.2.js
|
http://www.bkjia.com/PHPjc/632807.html www.bkjia.com true http://www.bkjia.com/PHPjc/632807.html techarticle recursive algorithm in PHP is not much of our data traversal method, let me introduce you to the use of recursion to do something. See a simple recursive instance ...