开发者

How do I sort a directory by time, and display the last four image files matching a pattern with php?

I have a directory that will be getting updated frequently, I want to display the last four images files uploaded, which match a certain pattern, on my php pag开发者_运维技巧e.

Is this possible without having to perform a sort on every single image within the directory?

Many thanks!


You'll always have to sort if you want the last four files, but you might as well let the filesystem do it for you. This will work on linux unless your pattern's a regex:

$pattern = '*.jpg';
exec( "ls $pattern -1t | head -4", $files );
foreach( $files as $thisFile ) {
    echo "<img src='", $serverPathToFiles, $thisFile, "' alt='blah' />\n";
}

If you have to use a regex, change the first two lines to

$pattern = 'web2\.[4-5]'; // for web2.42 etc.
exec( "ls -1t | grep -e $pattern | head -4", $files );


Dunno what do you call "to perform a sort on every single image within the directory", but you have to read all file names into array and then read ctime for the every file. and then sort the resulting array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜