dp20011 2014-12-07 14:01
浏览 28


Using this way, after the completion of DirectoryIterator cycle
you will get a list of filenames, and later you will be able to alphabetically sort it,
so that you can process each file with a filename from this list - in alphabetical order...

Now, what if, after the completion of DirectoryIterator cycle,
you need an array (alphabetically sorted by filename), that contains not only the filename,
but also all the other file properties, such as:

  • permissions
  • owner
  • time of creation
  • size
  • etc...

The problem here is, you cant sort before the completion of DirectoryIterator cycle,
and after it you will not be able to access anything other than filenames from your list...

  • 写回答

1条回答 默认 最新

  • douzuan5365 2014-12-07 14:01

    DirectoryIterator objects provide a simple way to access many of file properties.

    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileInfo) {
        if ((!$fileInfo->isDot())&&($fileInfo->GetExtension() == "txt")) {
            /* You can access the file information inside this cycle */
            $octal_perms = substr(sprintf('%o', $fileInfo->getPerms()), -4);
            echo $fileInfo->getFilename() . " " . $octal_perms . "

    If we need the fileInfo objects after the completion of DirectoryIterator cycle,
    we will have to clone (copy) all these DirectoryIterator objects into a new array,
    and then sort this array alphabetically by filename attribute of DirectoryIterator objects.

    function cmp($a, $b)
        return strcmp($a->getFilename(), $b->getFilename());
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileInfo) {
        if ((!$fileInfo->isDot())&&($fileInfo->GetExtension() == "txt")) {
            /* we need to clone a fileInfo object into array, not just assign it */
            $allFilesInfo[] = clone $fileInfo;
    /* Alphabetically sorting the array with DirectoryIterator objects, by filename */
    usort($allFilesInfo, 'cmp');
    foreach ($allFilesInfo as $fileInfo) {
        /* Everything is alphabetical here ;) */
        $octal_perms = substr(sprintf('%o', $fileInfo->getPerms()), -4);
        echo $fileInfo->getFilename() . " " . $octal_perms . "

    ^^ In this last cycle, you can work with your files in alphabetical order,
    while being able to access all their properties :)

    NOTE: in case of crash, caused by "too many open files" error,
    increase the max limit of open file descriptors per a process in your OS.
    Related config files are depend on your OS, and usually they're stored in /etc

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)