php glob() - 按日期排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/124958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:33:27  来源:igfitidea点击:

glob() - sort by date

php

提问by cole

I'm trying to display an array of files in order of date (last modified).

我正在尝试按日期(上次修改)的顺序显示文件数组。

I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this?

我已经完成了遍历数组并将其排序到另一个数组中的购买,但是有没有更简单(更有效)的方法来做到这一点?

回答by Jay

Warningcreate_function()has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

create_function()自 PHP 7.2.0 起,警告已被弃用。强烈建议不要依赖此功能。

For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is:

为后人着想,如果已接受答案中链接的论坛帖子丢失或某些人不清楚,则需要的相关代码是:

<?php

$myarray = glob("*.*");
usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));

?>

Tested this on my system and verified it does sort by file mtime as desired. I used a similar approach (written in Python) for determining the last updated files on my website as well.

在我的系统上对此进行了测试并验证它确实根据需要按文件 mtime 排序。我也使用了类似的方法(用 Python 编写)来确定我网站上最近更新的文件。

回答by Alf Eaton

<?php
$items = glob('*', GLOB_NOSORT);
array_multisort(array_map('filemtime', $items), SORT_NUMERIC, SORT_DESC, $items);

回答by fusion3k

This solution is same as accepted answer, updated with anonymous function1:

此解决方案与接受的答案相同,使用匿名函数1更新:

$myarray = glob("*.*");

usort( $myarray, function( $a, $b ) { return filemtime($a) - filemtime($b); } );


1Anonymous functionshave been introduced in PHP in 2010. Original answer is dated 2008.

1匿名函数已于 2010 年在 PHP 中引入。原始答案的日期为 2008 年。

回答by Sebastian

I know this thread is old, but this can be done with a better performance. The usort()in the accepted answer will call filemtime()a lot of times. PHP uses quicksort algorithm which has an average performance of 1.39*n*lg(n). The algorithm calls filemtime()twice per comparison, so we will have about 28 calls for 10 directory entries, 556 calls for 100 entries, 8340 calls for 1000 entries etc. The following piece of code works good for me and has a great performance:

我知道这个线程很旧,但这可以通过更好的性能来完成。该usort()在接受的答案将调用filemtime()了很多次。PHP 使用快速排序算法,平均性能为1.39*n*lg(n). 该算法filemtime()每次比较调用两次,因此我们将有大约 28 个调用 10 个目录条目,556 个调用 100 个条目,8340 个调用 1000 个条目等等。以下代码对我来说效果很好并且性能很好:

exec ( stripos ( PHP_OS, 'WIN' ) === 0 ? 'dir /B /O-D *.*' : 'ls -td1 *.*' , $myarray );

回答by Dharman

Since PHP 7.4the best solution is to use custom sort with arrow function:

PHP 7.4 开始,最好的解决方案是使用带有箭头函数的自定义排序:

usort($myarray, fn($a, $b) => filemtime($a) - filemtime($b));