温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP中对目录进行递归的方法有哪些

发布时间:2021-01-22 15:54:35 来源:亿速云 阅读:146 作者:Leah 栏目:开发技术

本篇文章为大家展示了PHP中对目录进行递归的方法有哪些,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

方法一:使用glob循环

<?php
//方法一:使用glob循环
 
function myscandir1($path, &$arr) {
 
  foreach (glob($path) as $file) {
    if (is_dir($file)) {
      myscandir1($file . '/*', $arr);
    } else {
 
      $arr[] = realpath($file);
    }
  }
}
?>

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

<?php
//方法二:使用dir && read循环
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);
    }
  }
}
?>

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

<?php
//方法三:使用opendir && readdir循环
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);
    }
  }
}
 ?>

 方法四:使用scandir循环
 

<?php
//方法四:使用scandir循环
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);
    }
  }
}
 ?>

方法五:使用SPL循环

 <?php
//方法五:使用SPL循环
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);
    }
  }
}
?>

 可以用xdebug测试运行时间

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

上述内容就是PHP中对目录进行递归的方法有哪些,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI