Home >Backend Development >PHP Tutorial >PHP method to sort files in a folder directory

PHP method to sort files in a folder directory

王林
王林Original
2019-12-02 14:14:203654browse

PHP method to sort files in a folder directoryphp implements the method of sorting files in a folder directory according to time, name, and size

Function introduction:

opendir() Function Open a directory handle.

readdir() The function returns the file name of the next file in the directory.

array_multisort() The function returns a sorted array. You can enter one or more arrays. The function sorts the first array first, then the other arrays, and if two or more values ​​are the same, it sorts the next array.

Learning video recommendation: php video tutorial

Examples are as follows:

function dir_size($dir,$url){
     $dh = @opendir($dir);             //打开目录,返回一个目录流     $return = array();
      $i = 0;
          while($file = @readdir($dh)){     //循环读取目录下的文件             
              if($file!='.' and $file!='..'){
                  $path = $dir.'/'.$file;     //设置目录,用于含有子目录的情况              
                  if(is_dir($path)){
          }elseif(is_file($path)){
              $filesize[] =  round((filesize($path)/1024),2);//获取文件大小              
              $filename[] = $path;//获取文件名称                                   
              $filetime[] = date("Y-m-d H:i:s",filemtime($path));//获取文件最近修改日期       
              $return[] =  $url.'/'.$file;
          }
          }
          }  
          @closedir($dh);             //关闭目录流          
              array_multisort($filesize,SORT_DESC,SORT_NUMERIC, $return);//按大小排序          
              //array_multisort($filename,SORT_DESC,SORT_STRING, $files);//按名字排序          
              //array_multisort($filetime,SORT_DESC,SORT_STRING, $files);//按时间排序          
              return $return;               //返回文件     
}

Recommended related article tutorials: php tutorial

The above is the detailed content of PHP method to sort files in a folder directory. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn