php DirectoryIterator按日期对文件进行排序 [英] php DirectoryIterator sort files by date

查看:78
本文介绍了php DirectoryIterator按日期对文件进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用php的DirectoryIterator类列出目录中的文件.但是,我想不出一种简单的方法来按日期对文件进行排序. DirectoryIterator如何实现

I'm using php's DirectoryIterator class to list files in a directory. I can't however figure out an easy way to sort files by date. How is this done with DirectoryIterator

<?php
 $dir = new DirectoryIterator('.');
  foreach ($dir as $fileinfo) {     
     echo $fileinfo->getFilename() . '<br>';
   }
?>

如果我将我的文件命名为what_2342345345.ext,那该怎么办?其中数字表示时间(以毫秒为单位),因此每个文件都有一个唯一的数字.我们如何通过查看下划线后的数字来进行排序

What if i name my files like whatever_2342345345.ext where the numbers represents time in milliseconds so each file has a unique number. How can we sort by looking at the numbers after underscore

推荐答案

如果需要排序,请构建一个数组并对其进行排序.

If you need to sort, build an array and sort that.

$files = array();
$dir = new DirectoryIterator('.');
foreach ($dir as $fileinfo) {     
   $files[$fileinfo->getMTime()][] = $fileinfo->getFilename();
}

ksort($files);

这将构建一个以修改后的时间为键的数组,并以文件名的数组作为值.然后,它通过 ksort() 进行排序,这将按以下顺序为您提供文件名时间已修改.

This will build an array with the modified time as the key and an array of filenames as the value. It then sorts via ksort(), which will give you the filenames in order of time modified.

如果您随后想要将结构重新展平为标准数组,则可以使用...

If you then want to re-flatten the structure to a standard array, you can use...

$files = call_user_func_array('array_merge', $files);

这篇关于php DirectoryIterator按日期对文件进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆