Examples of php recursive usage and Recursive directory

Source: Internet
Author: User

Look at a simple recursive instance

Example 1

The code is as follows: Copy code

Function demo ($ ){

Static $ sum = 1;

If ($ a> 1 ){

$ Sum * = $;

Demo (-- $ );

} Else {

$ A = $ sum;

        } 

Return $ sum;


 

Echo demo (10 );

Example 2

Traverse directories

The code is as follows: Copy code

<? Php
Class listdir {
Var $ depth;
Var $ dirname;
Var $ list;
Var $ tostring;

Function listdir ($ dir ){
$ This-> dirname = $ dir;
$ This-> depth = 0;
$ This-> tostring = "";
}

// Save the result to a multi-dimensional 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;
}

// Escape results

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 ();
?>

Output result:

<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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.