【问题标题】:After using usort on a DirectoryIterator, method calls don't seem to work anymore在 DirectoryIterator 上使用 usort 后,方法调用似乎不再起作用
【发布时间】:2018-06-22 15:00:45
【问题描述】:

我正在尝试创建一个基于日期删除最旧文件的函数,最多可删除 30 个文件。我抓取目录中的所有文件。如果超过 30 个,则按日期排序。然后最旧的被删除。

public function cleanUpFolder($path){
    $files = [];
    try {
        $dir = new DirectoryIterator($path);
        foreach ($dir as $fileinfo) {
            if (!$fileinfo->isDot()) {
                $files[] = $fileinfo;
                // in here i can call any valid method like getPathname()
            }
        }
        $fileCount = count($files);
        if($fileCount > self::MAX_BACKUPS){
            // sort with the youngest file first
            usort($files, function($a, $b) {
                // in here, i can call functions like getMTime()
                // and even getPath()
                // but getPathname or getFileName return false or ""
                return $a->getMTime() < $b->getMTime();
            });
            for($i = $fileCount - 1; $i > 30; $i--){
                unlink($files[$i]->getPathname());
            }
        }        
        return true;
    }
    catch (Exception $e){
        return false;
    }
}

什么是有效的

  1. 获取文件

什么不工作

  1. 排序?我无法判断排序是否有效

  2. 在遍历 $files 数组时调用 DirectoryIterator 上的一些方法

似乎将$fileInfo 放入数组中,大多数函数调用不再起作用..

【问题讨论】:

    标签: php


    【解决方案1】:

    我发现$files 数组的值在 foreach 循环之外被弄乱了。数组的var_dump 显示所有值都是空的,这很奇怪。不是真正的解决方案,而是我从this question 找到的解决方法:

    $files = array();
    $dir = new DirectoryIterator($path);
    foreach ($dir as $fileinfo) {
        if (!$fileinfo->isDot()) {
            $files[] = array(
                "pathname" => $fileinfo->getPathname(),
                "modified" => $fileinfo->getMTime()
            );
        }
    }
    

    然后你的usort 变成:

    usort($files, function($a, $b) {
        return $a['modified'] < $b['modified'];
    });
    

    你的unlink变成:

    for($i = $fileCount - 1; $i > 30; $i--){
        unlink($files['pathname']);
    }
    

    === 编辑 ===

    我不是 PHP 专家,所以这可能是错误的,但 FilesystemIterator 的顶部评论可能是关于为什么方法返回空的线索。

    当您使用 DirectoryIterator 进行迭代时,返回的每个“值”都是 相同的 DirectoryIterator 对象。内部状态改变了 当您调用 isDir()、getPathname() 等时,正确的信息是 回来。如果你在迭代时要求一个密钥,你会得到一个 整数索引值。

    另一方面,FilesystemIterator(和 RecursiveDirectoryIterator) 为每个迭代步骤返回一个新的、不同的 SplFileInfo 对象。 关键是文件的完整路径名。这是默认设置。你可以 使用“标志”更改键或值返回的内容 与构造函数争论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多