简体   繁体   中英

Sort PHP image gallery with the newest First

I am using a php code to display list of product from one product folder for website http://zemro.in/products.php

Whenever new picture is added it should show the first

below is the code i am using on the page.

<div id="galleryListWrapper">
    <?php if (!empty($galleryArray) && $galleryArray['stats']['total_images'] > 0): ?>
        <ul id="galleryList" class="clearfix">
            <?php foreach ($galleryArray['images'] as $image): ?>
                <li><a href="<?php echo html_entity_decode($image['file_path']); ?>" title="<?php echo $image['file_title']; ?>" rel="colorbox"><img src="<?php echo $image['thumb_path']; ?>" alt="<?php echo $image['file_title']; ?>"/></a></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
</div>

When getting your files from the directory, add a key for the creation date of the file in the file's array. For sorting purposes it's probably enough to just use filemtime( $filepath ).

...
$image[ 'timestamp' ] = filemtime( $image[ 'file_path' ] );
...

To then sort your array by the timestamp, have a look at Sort Multi-dimensional Array by Value

For your purposes, it would look something like this:

function sortByTimestamp( $a, $b ) {
    if ($a[ 'timestamp' ] == $b[ 'timestamp' ]) {
        return 0;
    }
    return ($a[ 'timestamp' ] > $b[ 'timestamp' ]) ? -1 : 1;
}

usort( $galleryArray[ 'images' ], 'sortByTimestamp' );

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