Home >Backend Development >PHP Problem >How to sort php files by modification time

How to sort php files by modification time

藏色散人
藏色散人Original
2021-12-10 09:37:412572browse

How to sort PHP files by modification time: 1. Traverse the files in the directory through the "function printdir($dir){...}" method; 2. Use the "function arraysort($aa) {. ..}" method can sort the returned array by modification time.

How to sort php files by modification time

#The operating environment of this article: Windows 7 system, PHP version 7.4, Dell G3 computer.

php How to sort files by modification time?

php Traverse files in a directory and sort them by modification time Operation example

php Method of traversing files in a directory :

//遍历目录下文件方法
function printdir($dir)
{
    $files = array();
    //opendir() 打开目录句柄
    if($handle = @opendir($dir)){
    //readdir()从目录句柄中(resource,之前由opendir()打开)读取条目,
    // 如果没有则返回false
        while(($file = readdir($handle)) !== false){//读取条目
            if( $file != ".." && $file != "."){//排除根目录
                if(is_dir($dir . "/" . $file)) {//如果file 是目录,则递归
                    $files[$file] = printdir($dir . "/" . $file);
                } else {
                    //获取文件修改日期
                    $filetime = date('Y-m-d H:i:s', filemtime($dir . "/" . $file));
                    //文件修改时间作为健值
                    $files[$filetime] = $file;
                }
            }
        }
        @closedir($handle);
        return $files;
    }
}

Sort the returned array by time

//根据修改时间对数组排序
function arraysort($aa) {
    if( is_array($aa)){
        ksort($aa);
        foreach($aa as $key => $value) {
            if (is_array($value)) {
                $arr[$key] = arraysort($value);
            } else {
                $arr[$key] = $value;
            }
        }
        return $arr;
    } else {
        return $aa;
    }
}
$dir = "/php";
//输出 /php 下所有文件
print_r(arraysort(printdir($dir)));

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to sort php files by modification time. 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
Previous article:How to reverse php arrayNext article:How to reverse php array