【问题标题】:how to put all files from folder and subfolders into an array如何将文件夹和子文件夹中的所有文件放入数组中
【发布时间】:2021-02-17 07:21:03
【问题描述】:

我正在使用此功能从文件夹及其子文件夹中获取所有文件。这很好用。但我需要所有这些文件的数组。

 function get_all_directory_and_files($dir){
 
     $dh = new DirectoryIterator($dir);   
     // Dirctary object 
     foreach ($dh as $item) {
         if (!$item->isDot()) {
            if ($item->isDir()) {
                get_all_directory_and_files("$dir/$item");
            } else {
                echo $dir . "/" . $item->getFilename();
                echo "<br>";
            }
         }
      }
   }
 
  # Call function 
  
  get_all_directory_and_files("data/comments");

那么我怎样才能将所有文件放入这样的数组中:

$all_files[] = // contains all the files

【问题讨论】:

    标签: php arrays file


    【解决方案1】:
    <?php
    
    function get_all_directory_and_files($dir) {
        $results = [];
        $dh = new DirectoryIterator($dir);   
        // Dirctary object 
        foreach ($dh as $item) {
            if (!$item->isDot()) {
                if ($item->isDir()) {
                    $results = array_merge($results, get_all_directory_and_files($dir . DIRECTORY_SEPARATOR . $item));
                } else {
                    $results[] = $dir . DIRECTORY_SEPARATOR . $item->getFilename();
                }
            }
        }
    
        return $results;
    }
    
    var_dump( get_all_directory_and_files("/tmp") );
    
    

    【讨论】:

      猜你喜欢
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      相关资源
      最近更新 更多