我有以下php脚本显示目录
中的所有图像<?php
$images = glob($dirname."*.jpg");
foreach($images as $image) {
echo '<img src="'.$image.'" height ="400"/><br />';
}
?>
我想修改这个,这样当你访问页面时,它会显示最后修改的图像在顶部。有人能告诉我该怎么做吗?
可以使用filemtime()
函数查找每个文件的修改日期。这可以用作在循环中处理之前使用uksort()
对数组进行排序的键。
这将按照文件修改时间的升序排列数组,即mtime最早的优先。然后,您可以反转该数组,也可以向后遍历该数组。
<?php
function mtimecmp($a, $b) {
$mt_a = filemtime($a);
$mt_b = filemtime($b);
if ($mt_a == $mt_b)
return 0;
else if ($mt_a < $mt_b)
return -1;
else
return 1;
}
$images = glob($dirname."*.jpg");
usort($images, "mtimecmp");
$images=array_reverse($images);
foreach ($images as $image) {
echo '<img src="'.$image.'" height ="400"/><br />';
}
?>
(向后迭代更有效…)
// ...
usort($images, "mtimecmp");
for ($i = count($images) - 1; $i >= 0; $i--) {
$image = $images[$i];
echo '<img src="'.$image.'" height ="400"/><br />';
}
您需要分两步执行:(a)读取目录内容并记录最后修改的信息(b)呈现结果
$images = glob($dirname . '*.jpg');
$mostrecent = 0;
$mostrecentimg = null;
// scan
foreach ($images as $image) {
$imagemod = filemtime($image);
if ($mostrecent < $imagemod) {
$mostrecentimg = $image;
$mostrecent = $imagemod;
}
}
// display
echo '<img src="' . $mostrecentimg . '" height="400"/><br />';
foreach($images as $image) {
// the most recent was already output above so skip remainder this iteration
if ($image == $mostrecentimg) continue;
echo '<img src="' . $image . '" height="400"/><br />';
}