在PHP中使用$ files = new DirectoryIterator()之后,如何对项目进行排序? [英] after using $files = new DirectoryIterator() in PHP, how do you sort the items?

查看:73
本文介绍了在PHP中使用$ files = new DirectoryIterator()之后,如何对项目进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以通过以下方式在PHP目录中获取文件

We can get the files in a directory in PHP by

$files = new DirectoryIterator() 

之后,是否有一种简单的方法可以按特定顺序对项目进行排序以显示它们?谢谢.

after that is there an easy way to sort the items in a particular order for displaying them? thanks.

推荐答案

似乎没有一种方法可以对迭代器中的数据进行排序.

It doesn't look like there is a way to sort the data within the iterator.

您可以将显示数据放入一个中间数组,并使用您希望排序的值的键,然后在该数组上调用ksort().但是,这将需要两次传递数据.

You could place the display data into an intermediary array, with a key of the value you wish to sort by, and call ksort() on the array. This will take two passes over the data however.

$path = ".";
$files = new DirectoryIterator($path);
$files_array = array();

while($files->valid()) {
        // sort key, ie. modified timestamp
        $key = $files->getMTime();
        $data = $files->getFilename();
        $files_array[$key] = $data;
        $files->next();
}
ksort($files_array);
foreach($files_array as $key => $file){
    print $key . " => " . $file . "\n";
}

如果将要为文件输出的所有信息都放在数组值中,则只需在之后将implode()插入数组,而不必再次遍历数据.

if you place all of the information that you want to output for the files in the array values, you can simply implode() the array afterwards, instead of looping through the data once again.

这篇关于在PHP中使用$ files = new DirectoryIterator()之后,如何对项目进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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