在php目录中显示最新的图像


Display the latest images in a directory php

我看了一下,但只能找到如何显示最新的图像,或者全部显示。我需要显示5张最新的图片。感谢

我当前显示1个图像的代码是

<?php
$dir = 'images/other';
$base_url = '/images/other';
$newest_mtime = 0;
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if (($file != '.') && ($file != '..')) {
            $mtime = filemtime("$dir/$file");
            if ($mtime > $newest_mtime) {
                $newest_mtime = $mtime;
                $show_file = "$base_url/$file";
            }
        }
    }
}
print '<img src="' .$show_file. '" alt="code">';
?>

这应该适用于您:

(首先,我用glob()获取所有文件,并用filemtime()usort()按最后一次修改对其进行排序。之后,用array_slice()获取5个最新文件。最后,我只需循环浏览它们并打印图像)

<?php
    $dir = "images/other";
    $files = glob($dir . "/*.*");
    usort($files, function($a, $b){
        return (filemtime($a) < filemtime($b));
    });
    $files = array_slice($files, 0, 5);
    foreach($files as $file)
        echo "<img src='" . $file. "' alt='code'>";
?>