php scandir sorting by file date

2020-07-24 15:54发布

I need help, how to sort the code below, by file date?.

$dir2 = "flash/$plk/img";        
$plks2 = scandir($dir2);
$plkss2 = array_diff($plks2, array('.', '..'));      
       foreach ($plkss2 as $plk2) {
           echo '<img data-src="flash/'. str_replace('+', '%20', urlencode($plk)) .'/img/' . $plk2 . '" alt="" class="img-responsive lazyload">';
       }

标签: php
2条回答
我想做一个坏孩纸
2楼-- · 2020-07-24 16:31

This should work for you:

(I just get all files of the directory with glob(), then I sort the array with usort(), where I use filemtime() to compare the last modification and the I loop through every file with the foreach loop)

<?php

    $files = glob("flash/$plk/img/*.*");
    usort($files, function($a, $b){
        return filemtime($a) < filemtime($b);
    });

    foreach ($files as $plk2) {
       echo '<img data-src="flash/' . str_replace('+', '%20', urlencode($plk)) . '/img/' . $plk2 . '" alt="" class="img-responsive lazyload">';
    }


?>
查看更多
够拽才男人
3楼-- · 2020-07-24 16:36

here you go

<?php

$dir = ".";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

$file_array = array();
foreach ($files as $file_name) {
    $file_array[filemtime($file_name)] = $file_name;
}
ksort($file_array);
var_dump($file_array);

?>
查看更多
登录 后发表回答