当前位置:Gxlcms > PHP教程 > PHP实现递归目录的5种方法

PHP实现递归目录的5种方法

时间:2021-07-01 10:21:17 帮助过:43人阅读

本篇文章主要介绍了PHP实现递归目录的5种方法,主要是利用一些循环来实现的,感兴趣的小伙伴们可以参考一下。

项目开发中免不了要在服务器上创建文件夹,比如上传图片时的目录,模板解析时的目录等。这不当前手下的项目就用到了这个,于是总结了几个循环创建目录的方法。

方法一:使用glob循环

  1. <?php
  2. //方法一:使用glob循环
  3. function myscandir1($path, &$arr) {
  4. foreach (glob($path) as $file) {
  5. if (is_dir($file)) {
  6. myscandir1($file . '/*', $arr);
  7. } else {
  8. $arr[] = realpath($file);
  9. }
  10. }
  11. }
  12. ?>

方法二:使用dir && read循环

  1. <?php
  2. //方法二:使用dir && read循环
  3. function myscandir2($path, &$arr) {
  4. $dir_handle = dir($path);
  5. while (($file = $dir_handle->read()) !== false) {
  6. $p = realpath($path . '/' . $file);
  7. if ($file != "." && $file != "..") {
  8. $arr[] = $p;
  9. }
  10. if (is_dir($p) && $file != "." && $file != "..") {
  11. myscandir2($p, $arr);
  12. }
  13. }
  14. }
  15. ?>

方法三:使用opendir && readdir循环

  1. <?php
  2. //方法三:使用opendir && readdir循环
  3. function myscandir3($path, &$arr) {
  4. $dir_handle = opendir($path);
  5. while (($file = readdir($dir_handle)) !== false) {
  6. $p = realpath($path . '/' . $file);
  7. if ($file != "." && $file != "..") {
  8. $arr[] = $p;
  9. }
  10. if (is_dir($p) && $file != "." && $file != "..") {
  11. myscandir3($p, $arr);
  12. }
  13. }
  14. }
  15. ?>

方法四:使用scandir循环

  1. <?php
  2. //方法四:使用scandir循环
  3. function myscandir4($path, &$arr) {
  4. $dir_handle = scandir($path);
  5. foreach ($dir_handle as $file) {
  6. $p = realpath($path . '/' . $file);
  7. if ($file != "." && $file != "..") {
  8. $arr[] = $p;
  9. }
  10. if (is_dir($p) && $file != "." && $file != "..") {
  11. myscandir4($p, $arr);
  12. }
  13. }
  14. }
  15. ?>

方法五:使用SPL循环

  1. <?php
  2. //方法五:使用SPL循环
  3. function myscandir5($path, &$arr) {
  4. $iterator = new DirectoryIterator($path);
  5. foreach ($iterator as $fileinfo) {
  6. $file = $fileinfo->getFilename();
  7. $p = realpath($path . '/' . $file);
  8. if (!$fileinfo->isDot()) {
  9. $arr[] = $p;
  10. }
  11. if ($fileinfo->isDir() && !$fileinfo->isDot()) {
  12. myscandir5($p, $arr);
  13. }
  14. }
  15. }
  16. ?>

可以用xdebug测试运行时间

  1. <?php
  2. myscandir1('./Code',$arr1);//0.164010047913
  3. myscandir2('./Code',$arr2);//0.243014097214
  4. myscandir3('./Code',$arr3);//0.233012914658
  5. myscandir4('./Code',$arr4);//0.240014076233
  6. myscandir5('./Code',$arr5);//0.329999923706
  7. //需要安装xdebug
  8. echo xdebug_time_index(), "\n";
  9. ?>

以上就是本文的全部内容,希望对大家的学习有所帮助。


相关推荐:

PHP实现的Redis多库选择功能单例类(详解)

PHP自定义函数判断是否为Get/Post/Ajax提交的方法详解

php自动备份数据库表的方法

以上就是PHP实现递归目录的5种方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行