首页 > 解决方案 > PHP - 按修改日期排序的目录列表

问题描述

这是我目前从(Apache)服务器获取文件列表并将它们排序为反向修改顺序的努力。

它完美无缺,但为什么反向排序不适用于目录列表?它很好地列出了它们,但没有订购它们。

<?php 
function getFiles(){
    $files=array();
    if($dir=opendir('.')){
        while($file=readdir($dir)){
            if (!in_array($file,array(".","..","index.php"))) {
                $files[]=$file;
            }
        }

        closedir($dir);

    }
    
    rsort($files); ##sort reverse modified
    return $files;
}
}
?>

标签: php

解决方案


function getFiles()
{
    $files = array();
    //put files in an array both have same modified time 
    $atSameTimes = [];
    if ($dir = opendir('.')) {
        while ($file = readdir($dir)) {
            if (!in_array($file, array(".", "..", "index.php"))) {
                if (isset($files[filemtime($file)])) {
                    if (isset($atSameTimes[filemtime($file)]) && is_array($atSameTimes[filemtime($file)])) {
                        $atSameTimes[filemtime($file)][] = $file;
                    } else {
                        $atSameTimes[filemtime($file)][] = $files[filemtime($file)];
                        $atSameTimes[filemtime($file)][] = $file;
                    }
                } else {
                    $files[filemtime($file)] = $file;
                }
            }
        }
        closedir($dir);
    }
    
    $arr = array_replace_recursive($files, $atSameTimes);
    ksort($arr, SORT_NUMERIC); ##Sort an array in descending order and maintain index association
    //asort($arr); ##Sort an array in ascending order and maintain index association
    return $arr;
}

样本输出:

array(4) {
    [1577562574]=>
    array(3) {
      [0]=>
      string(15) "CONTRIBUTING.md"
      [1]=>
      string(9) "README.md"
      [2]=>
      string(11) "phpunit.xml"
    }
    [1607445739]=>
    array(3) {
      [0]=>
      string(7) "LICENSE"
      [1]=>
      string(13) "composer.json"
      [2]=>
      string(12) "CHANGELOG.md"
    }
    [1612604942]=>
    string(19) "LoginController.php"
    [1622636168]=>
    string(19) "StoreController.php"
  }

推荐阅读