php - 按最新日期排序文件在顶部使用 RecursiveDirectoryIterator

标签 php file sorting

现在默认按字母显示,我不希望那样。我想在顶部使用 RecursiveDirectoryIterator 最新文件对文件进行排序。按降序排列。

同时使用 if 条件比较日期并从该日期获取文件

   <?php
    $search_path = 'D:\xampp\htdocs';
    $file_extension = 'php';
    $it = new RecursiveDirectoryIterator("$search_path");
    $display = Array ($file_extension);


    foreach(new RecursiveIteratorIterator($it) as $file) {
        $test = Array();
        $test = explode("/",date("m/d/Y",filemtime($file)));
        $year = $test[2];
        $day = $test[1];
        $month = $test[0];


    if (in_array(strtolower(array_pop(explode('.', $file))), $display))
             if(($year >= 2014) && ($month >= 1) && ($day >= 15 )){
                   echo "<span style='color:red;'>";
                   echo "<b  style='color:green;'>".$day.'-'.$month.'-'.$year. '</b> ' . $file."</span><br>";
             }
        } 

    ?>

最佳答案

我不知道您是否可以直接通过 DirectoryIterator 进行排序,您可以先收集结果,获取时间,然后排序,然后呈现它。示例:

$display = array('php');
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($search_path));
$data = array();
foreach($files as $file) {
    $time = DateTime::createFromFormat('U', filemtime($file->getPathname()));
    // no need to explode the time, just make it a datetime object
    if(in_array($file->getExtension(), $display) && $time > new DateTime('2014-01-15')) { // is PHP and is greater than jan 15 2014
        $data[] = array('filename' => $file->getPathname(), 'time' => $time->getTimestamp()); // push inside
    }

}
usort($data, function($a, $b){ // sort by time latest
    return $b['time'] - $a['time'];
});


foreach ($data as $key => $value) {
    $time = date('Y-m-d', $value['time']);
    echo "
        <span style='color: red;'>
            <b style='color: green;'>$time</b>$value[filename]
        </span>
        <br/>
    ";
}

关于php - 按最新日期排序文件在顶部使用 RecursiveDirectoryIterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601631/

相关文章:

c# - 无法使用 FileIOPermission 复制具有适当权限的文件

java - 数组返回 null .. 生成随机单词

java - TreeMap 和 TreeSet 排序不同步

php - 记录代码的软件?

java - 用java获取文件的第一行

php - 动态表单提交到数据库

ios - 如何在 tableView swift 中快速进行数组追加和排序

Bash:用指数对数字进行排序

php - 需要使用 SQL 查询设计网站搜索方面的帮助

javascript - 模板化仅采用标题/内容参数的 HTML 代码块的简洁方法,其中内容可能很大且散布着换行符