This article mainly introduces the PHP implementation of the recursive directory of 5 methods, mainly using a number of loops to achieve, interested in small partners can refer to.
Project development is unavoidable to create folders on the server, such as when uploading images of the directory, template parsing directory, and so on. This is not the current project to use this, so summed up a few loops to create a directory method.
Method One: Use the Glob loop
<?php//method One: Use the glob loop function Myscandir1 ($path, & $arr) { foreach (Glob ($path) as $file) { if (Is_dir ($ File) { Myscandir1 ($file. '/* ', $arr); } else { $arr [] = Realpath ($file);}} }? >
Method Two: Use dir && read loop
<?php//method Two: Use dir && read loop function Myscandir2 ($path, & $arr) { $dir _handle = dir ($path); while (($file = $dir _handle->read ())!== false) { $p = Realpath ($path. '/' . $file); if ($file! = "." && $file! = "...") { $arr [] = $p; } if (Is_dir ($p) && $file! = "." && $file! = "...") { Myscandir2 ($p, $arr);}} ? >
Method Three: Use Opendir && readdir loops
<?php//method Three: Use Opendir && readdir loop function Myscandir3 ($path, & $arr) { $dir _handle = Opendir ($path); While ($file = Readdir ($dir _handle))!== false) { $p = Realpath ($path. '/' . $file); if ($file! = "." && $file! = "...") { $arr [] = $p; } if (Is_dir ($p) && $file! = "." && $file! = "...") { myscandir3 ($p, $arr);}}} ?>
Method Four: Use the Scandir loop
<?php//method Four: Use Scandir loop function Myscandir4 ($path, & $arr) { $dir _handle = Scandir ($path); foreach ($dir _handle as $file) { $p = Realpath ($path. '/' . $file); if ($file! = "." && $file! = "...") { $arr [] = $p; } if (Is_dir ($p) && $file! = "." && $file! = "...") { myscandir4 ($p, $arr);}}} ?>
Method Five: Use SPL loops
<?php//method Five: Use SPL looping function Myscandir5 ($path, & $arr) { $iterator = new Directoryiterator ($path); foreach ($iterator as $fileinfo) { $file = $fileinfo->getfilename (); $p = Realpath ($path. '/' . $file); if (! $fileinfo->isdot ()) { $arr [] = $p; } if ($fileinfo->isdir () &&! $fileinfo->isdot ()) { myscandir5 ($p, $arr);}} ? >
Can test run time with Xdebug
<?phpmyscandir1 ('./code ', $arr 1),//0.164010047913 myscandir2 ('./code ', $arr 2);//0.243014097214 myscandir3 ('./ Code ', $arr 3);//0.233012914658 myscandir4 ('./code ', $arr 4);//0.240014076233myscandir5 ('./code ', $arr 5);// 0.329999923706 //need to install Xdebugecho Xdebug_time_index (), "\ n";? >
The above is the whole content of this article, I hope that everyone's study has helped.