如何从目录中获取图像文件并按上次修改顺序排序?
How to get image files from a directory and order by last modified?
我正在创建图片库,并希望我最近上传的图片位于最前面。
这是我目前拥有的:
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$supported_file = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
} else {
continue;
}
}
但我不确定如何让它按上次上传的顺序显示。
$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}",GLOB_BRACE);
$sorted_files=array(); /* a new array that have modification time as values
and files as keys the purpose is to sort files according to the values in reverse order */
foreach ($files as $file)
{
$sorted_files[$file]=filemtime($file);
}
arsort($sorted_files);
foreach ($sorted_files as $image=>$mtime)
{
echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
我正在创建图片库,并希望我最近上传的图片位于最前面。
这是我目前拥有的:
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$supported_file = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
} else {
continue;
}
}
但我不确定如何让它按上次上传的顺序显示。
$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}",GLOB_BRACE);
$sorted_files=array(); /* a new array that have modification time as values
and files as keys the purpose is to sort files according to the values in reverse order */
foreach ($files as $file)
{
$sorted_files[$file]=filemtime($file);
}
arsort($sorted_files);
foreach ($sorted_files as $image=>$mtime)
{
echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}