darylsummers
darylsummers

Reputation: 89

Sort images in date/time of order uploaded rather than alphabetically - PHP

I've written some PHP to call all images from a directory and display them on a HTML page. As the file names are randomly generated to be identified for our online inventory system, I need them to be displayed in order they were uploaded to the system.

Below is the code I have written so far, am I correct in thinking it needs an if statement adding to it? Any help appreciated!

$dirname = "../dashboard/uploads/$inventory/";
$images = glob($dirname."*.jpg");
foreach($images as $image) {
echo '<img src="'.$image.'" class="print-images">';
}

Upvotes: 0

Views: 607

Answers (1)

Edin Omeragic
Edin Omeragic

Reputation: 1968

You can try something like this:

$dirname = "../dashboard/uploads/$inventory/";
$images = glob($dirname."*.jpg");

$items = array();
foreach($images as $image) {
    $item = new stdClass;
    $item->time = filemtime($image);
    $item->image = $image;
    $items[] = $item;
}

function sortCallback($a,$b){
    if ($a->time > $b->time) return 1;
    if ($a->time < $b->time) return -1;
    return 0;
}

usort($items, "sortCallback");

foreach($items as $item) {
    echo '<img src="'.$item->image.'" class="print-images">';
}

You can change filemtime function to filectime if you want date when image is created, also in sortCallback function you can change sort order.

It' may contain errors as I have not tested it.

Upvotes: 1

Related Questions