Php 作为数组中的键返回递归迭代器输出

Php 作为数组中的键返回递归迭代器输出,php,Php,我正在编写一个脚本,该脚本递归地获取服务器中在修改日期的某个特定时间之前已修改的所有文件,按修改日期排序并打印它们 代码,无需订购即可正常工作: <?php try { $rootdir = $_SERVER['DOCUMENT_ROOT']; $raw = new RecursiveDirectoryIterator($rootdir); $cooked = array(); $yesdate = strtotime("-5 year"); for

我正在编写一个脚本,该脚本递归地获取服务器中在修改日期的某个特定时间之前已修改的所有文件,按修改日期排序并打印它们

代码,无需订购即可正常工作:

<?php
try {
    $rootdir = $_SERVER['DOCUMENT_ROOT'];
    $raw = new RecursiveDirectoryIterator($rootdir);
    $cooked = array();
    $yesdate = strtotime("-5 year");
    foreach(new RecursiveIteratorIterator($raw) as $file) {
        if (filemtime($file) >= $yesdate) {
            $cooked[] = $file;
        }
    } 
    foreach($cooked as $file) {
        echo date("F d Y H:i:s.", filemtime($file)) . $file . ' ' . '<br />';
    }    
} catch (Exception $ex) {
    echo $ex->getMessage();
}

如果查看第二个示例的错误日志,您可能会看到很多类似的条目

PHP警告:在/home/…中输入非法偏移量。。。第9行
PHP堆栈跟踪:
PHP1。{main}()/home/

第9行是构建数组元素的位置:

$cooked[$file] = filemtime($file);
问题在于
$file
这里不是字符串,而是
SplFileInfo
的一个实例。这在您的第一个示例中起作用,因为该类实现了
\uu toString
,这意味着
filemtime
可以处理它。但将其直接用作数组密钥是行不通的

简单的解决方法是在添加元素时手动将其转换为字符串:

$cooked[(string) $file] = filemtime($file);
另一个(更好的?)选项是使用第二个构造函数参数
recursivedirectoryinterator
,它告诉它首先只给您文件名:

$raw = new RecursiveDirectoryIterator($rootdir, FilesystemIterator::CURRENT_AS_PATHNAME);

如果查看第二个示例的错误日志,您可能会看到很多类似的条目

PHP警告:在/home/…中输入非法偏移量。。。第9行
PHP堆栈跟踪:
PHP1。{main}()/home/

第9行是构建数组元素的位置:

$cooked[$file] = filemtime($file);
问题在于
$file
这里不是字符串,而是
SplFileInfo
的一个实例。这在您的第一个示例中起作用,因为该类实现了
\uu toString
,这意味着
filemtime
可以处理它。但将其直接用作数组密钥是行不通的

简单的解决方法是在添加元素时手动将其转换为字符串:

$cooked[(string) $file] = filemtime($file);
另一个(更好的?)选项是使用第二个构造函数参数
recursivedirectoryinterator
,它告诉它首先只给您文件名:

$raw = new RecursiveDirectoryIterator($rootdir, FilesystemIterator::CURRENT_AS_PATHNAME);