Php recursively traversing the file tree code

Source: Internet
Author: User


> ../B. php Tutorial and ../a. php, the results will appear twice in the scan report, which is very strange.

 

The code is as follows: Copy code

// Update at 2010.07.25-the following code is invalid:
$ Path = '..';
Function get_filetree_scandir ($ path ){
$ Tree = array ();
Foreach (scandir ($ path) as $ single ){
If (is_dir ('../'. $ single )){
$ Tree = array_merge ($ tree, get_filetree ($ single ));
}
Else {
$ Tree [] = '../'. $ single;
}
}
Return $ tree;
}
Print_r (get_filetree_scandir ($ path ));

// Update at 2010.07.25-The following is the new code.
$ Path = './';
Function get_filetree_scandir ($ path ){
$ Result = array ();
$ Temp = array ();
If (! Is_dir ($ path) |! Is_readable ($ path) return null; // Check the directory validity
$ Allfiles = scandir ($ path); // Obtain all files and folders in the directory
Foreach ($ allfiles as $ filename) {// traverse the files and folders in the directory
If (in_array ($ filename, array ('.', '..') continue; // Ignore. And ..
$ Fullname = $ path. '/'. $ filename; // obtain the complete file path.
If (is_dir ($ fullname) {// if it is a directory, continue recursion
$ Result [$ filename] = get_filetree_scandir ($ fullname); // start recursion
}
Else {
$ Temp [] = $ filename; // if it is a file, it is saved to an array.
}
}
Foreach ($ temp as $ tmp) {// save the content of the temporary array to the array that saves the result
$ Result [] = $ tmp; // in this way, the folder is placed in front of the file
}
Return $ result;
}
Print_r (get_filetree_scandir ($ path ));

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.