简体   繁体   中英

how to show last 10 uploaded images from a folder with php

I am new to php. I need to list 10 last uploaded images from a folder. now I have this code.

<?php
$imageDir = "uploads/";
$images = glob($imageDir.'*.jpg');
$flag=1;
foreach ($images as $image){
  echo '<div class="item' .($flag?' active image-resposive':''). '">'.PHP_EOL."\t\t";
?>
<img class="wow zoomIn image-resposive" src="<?php echo $image ?>" alt=""></div> 
<?php 
  $flag=0;
}
?>

Use opendir() to loop through the directory and store all image filenames with last modified date in an array. Sort this array and pick 10 images so that you get your 10 most recent ones.

How about this.

$imageDir = "Uploads/";
$images = glob($imageDir . '\*.jpg');

$latest = array();

foreach($images as $image) {

    $x = (string)filectime($image);
    // Incase you encounter duplicates
    // $x = (string)filectime($image) . $image;

    $latest[$x] = $image;
}

krsort($latest);
$latest = array_slice(array_values($latest), 0, 10);

var_dump($latest);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM