【问题标题】:How can i foreach files from folder and sort them by date?我如何从文件夹中获取文件并按日期对它们进行排序?
【发布时间】:2018-08-19 18:33:00
【问题描述】:

我有一个文件夹,我每天都会在其中上传照片,它们会显示在我网站的网页上,例如画廊。 问题是最后上传的照片没有显示在顶部,因为它们是按名称而不是按日期排序的。

是否可以按日期对它们进行排序,然后在页面上显示它们?

<?php
                $files = (glob("../catalog-reseller/wall/diverse/*.jpg")); rsort($files);
                foreach (array_slice($files, 0) as $filename) 
                {   $x=$x+1;
                    echo'
                    <a href="'.$filename.'" data-rel="lightcase:gallery" title="Caption Text">
                    <img src="'.$filename.'" alt="">
                </a>';
                 if($x==50){break;}
                }
?>

【问题讨论】:

标签: php image sorting foreach


【解决方案1】:

您可以使用filectime($filename) 查看文件的创建时间,然后使用usort 根据创建时间进行自定义排序。如果您想首先显示最新文件,请执行以下操作。

//usort expects a custom comparison function that takes two arguments
//custom function should return a number >= 1 if first_arg > second_arg
//custom function should return 0 if first_arg == second_arg
//and lastly, it should return a number < 0 if first_arg < second_arg

function compare($firstFile, $secondFile)
{
    return filectime($firstFile) - filectime($secondFile);
}

usort($files, "compare");

您可以找到 usort here 的文档和 filectime here. 的文档

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 2019-11-23
    • 2021-09-07
    • 2010-09-26
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多