我怎样才能在顶部对我的最新内容进行排序


How can I sort my the latest on top

我在YT上发现了一个php代码来显示目录中的图像。一切都很完美,但我需要在顶部显示最新照片。谁能帮我?

<?php
    $dir = 'foto';
    $file_display = array('jpg', 'jpeg');
    if (file_exists($dir) == false) {
        echo 'Gallery ''', $dir, ''' not found!';
    } else {
        $dir_contents = scandir($dir);
        foreach ($dir_contents as $file) {
            $file_type = strtolower (end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
                echo '<div id="', $file,  '"><img src="', $dir, '/', $file, '" alt="', $file, '" /></div>';
            }
        }
    }
?>

更少的代码:

array_multisort((
    array_map(
        'filemtime', ($files = glob(
            "$dir/*.{jpg,jpeg}", GLOB_BRACE)))), SORT_DESC, $files);
  • 特定文件的 glob 并存储在$files
  • 获取每个文件修改时间,并根据时间对$files进行排序

foreach $files和显示。

我认为您需要按日期对图像进行排序。有人在这里编写了scandir()函数的另一个变体:https://stackoverflow.com/a/11923516/1644017

您可以获取该函数并将$dir_contents = scandir($dir);更改为:代码中的$dir_contents = scan_dir($dir);