使用最新的“优先”对 PHP 图像库进行排序


Sort PHP image gallery with the newest First

我正在使用 php 代码显示一个产品文件夹中的产品列表,以供网站 http://zemro.in/products.php

每当添加新图片时,它应该显示第一个

以下是我在页面上使用的代码。

<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>

从目录中获取文件时,请在文件数组中添加文件的创建日期键。出于排序目的,只需使用 filemtime( $filepath 就足够了。

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

然后要按时间戳对数组进行排序,请查看按值对多维数组进行排序

出于您的目的,它看起来像这样:

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