首頁  >  文章  >  後端開發  >  PHP實作遞歸目錄的5種方法

PHP實作遞歸目錄的5種方法

墨辰丷
墨辰丷原創
2018-05-31 10:13:001707瀏覽

本篇文章主要介紹了PHP實作遞歸目錄的5種方法,主要是利用一些循環來實現的,有興趣的小夥伴們可以參考一下。

專案開發中免不了要在伺服器上建立資料夾,例如上傳圖片時的目錄,模板解析時的目錄等。這不當前手下的專案就用到了這個,於是總結了幾個循環創建目錄的方法。

方法一:使用glob循環

#
<?php
//方法一:使用glob循环
 
function myscandir1($path, &$arr) {
 
  foreach (glob($path) as $file) {
    if (is_dir($file)) {
      myscandir1($file . &#39;/*&#39;, $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 . &#39;/&#39; . $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 . &#39;/&#39; . $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 . &#39;/&#39; . $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 . &#39;/&#39; . $file);
    if (!$fileinfo->isDot()) {
      $arr[] = $p;
    }
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
      myscandir5($p, $arr);
    }
  }
}
?>

# 可以用xdebug測試運行時間


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

以上就是本文的全部內容,希望對大家的學習有幫助。

相關推薦:

PHP實作的Redis多庫選擇功能單例類別(詳解)

######PHP自訂函數判斷是否為Get/Post/Ajax提交的方法詳解###################php###自動備份資料庫表的方法###########################

以上是PHP實作遞歸目錄的5種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn