【问题标题】:How can I sort my image - the latest on top如何对我的图像进行排序 - 最新的在顶部
【发布时间】:2013-10-14 16:13:38
【问题描述】:

我在 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>';
            }
        }
    }
?>

【问题讨论】:

标签: php image


【解决方案1】:

更少的代码:

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

foreach$files 并显示。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-18
      • 2017-04-06
      • 2012-03-18
      • 2015-02-14
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      相关资源
      最近更新 更多