让RecursiveIteratorIterator跳过指定的目录

时间:2015-02-12 04:10:03

标签: php

我正在使用此功能来获取文件大小&来自给定目录的文件计数:

function getDirSize($path) {
    $total_size = 0;
    $total_files = 0;

    $path = realpath($path);
    if($path !== false){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
            $total_size += $object->getSize();
            $total_files++;
        }
    }

    $t['size'] = $total_size;
    $t['count'] = $total_files;
    return $t;
}

我需要跳过一个目录(在$ path的根目录中)。有一个简单的方法吗?我查看了FilterIterator的其他答案,但我对它并不熟悉。

1 个答案:

答案 0 :(得分:1)

如果您不想涉及FilterIterator,可以添加简单路径匹配:

function getDirSize($path, $ignorePath) {
    $total_size = 0;
    $total_files = 0;

    $path = realpath($path);
    $ignorePath = realpath($path . DIRECTORY_SEPARATOR . $ignorePath);

    if($path !== false){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object) {
            if (strpos($object->getPath(), $ignorePath) !== 0) {
                $total_size += $object->getSize();
                $total_files++;
            }
        }
    }

    $t['size'] = $total_size;
    $t['count'] = $total_files;
    return $t;
}

// Get total file size and count of current directory,
// excluding the 'ignoreme' subdir
print_r(getDirSize(__DIR__ , 'ignoreme'));