【问题标题】:How to sort images by date modified?如何按修改日期对图像进行排序?
【发布时间】:2017-08-28 16:32:08
【问题描述】:

此代码按字母顺序对图像进行排序。如何按日期排序?这样用户查看新图片会更方便。

代码如下:

<link href="assets/css/gallery.css" rel="stylesheet">
<link href="assets/css/dope.css" rel="stylesheet">
<div class="row center">
    <ul class="uk-tab" id="gamemodelistregion" uk-switcher="connect: + ul; animation: uk-animation-fade">
    <li aria-expanded="true" class="uk-active">
        <a>All skins</a>
        <?php
            # Skin directory relative to include/gallery.php (this file)
            $skindir = "../skins/";

            # Skin directory relative to index.html
            $skindirhtml = "./skins/";

            $images = scandir($skindir);

            foreach($images as $curimg) {
                if (strtolower(pathinfo($curimg, PATHINFO_EXTENSION)) == "png") {
        ?>
        <li class="skin" onclick="$('#nick').val('{' + $(this).find('.title').text() + '} ');" data-dismiss="modal">
            <div class="circular" style='background-image: url("./<?php echo $skindirhtml.$curimg ?>")'></div>
            <h4 class="title"><?php echo pathinfo($curimg, PATHINFO_FILENAME); ?></h4>
        </li>
        <?php
                }
            }
        ?>
    </li>
</ul>
</div>

【问题讨论】:

标签: php


【解决方案1】:

filemtime 函数返回文件最后修改日期的 Unix 时间戳。

// retrieve all images but don't waste time putting them in alphabetical order
$images = scandir($skindir, SCANDIR_SORT_NONE);

// remove all non-existent files and non-PNG files
$images = array_filter($images,
  function($file) use ($skindir) {
    $path = "$skindir/$file";
    return file_exists($path) && strtolower(pathinfo($path, PATHINFO_EXTENSION)) == "png";
  }
);

// sort image by modification time in descending order
usort($images, function($a,$b){return filemtime($a)-filemtime($b);});

// now you can iterate through images and print them
foreach($images as $curimg): ?>
  <!-- Output image HTML here -->
<?php
endforeach;

【讨论】:

  • 不工作。没有错误,没有显示图片和标题。
  • @salathe 你为什么做这个编辑?在 OP 代码中——实际上是显示图像,只是顺序错误——pathinfo 函数被提供给$images 的每个成员。我就是这么做的
  • @TopoR 请立即尝试。
  • 我添加了代码,这里是它的工作原理agarix.esy.es/include/gallery.php
  • @BeetleJuice 因为scandir() 仅返回文件(和目录)名称列表; file_exists()pathinfo() 函数将不会查看扫描的目录,如果您只向它们传递名称。我怀疑 OP 的代码“工作”只是偶然或巧合,如果它在工作的话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 2021-11-02
  • 2016-03-25
  • 2012-09-02
  • 2021-06-18
  • 2020-12-08
相关资源
最近更新 更多