文件到数组 - glob vs RecursiveIteratorIterator

时间:2017-05-31 19:36:10

标签: php arrays iterator

我正在通过执行以下操作向文件添加文件列表:

$files = glob($path."*.*");

我可以使用print_r(array_values($array));输出数组。

现在我正尝试对RecursiveIteratorIterator执行相同的操作:

$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path)
);

当我尝试输出数组时,这不会像预期的那样工作吗?

print_r(array_values($files));

我怎样才能得到相同的结果?

1 个答案:

答案 0 :(得分:1)

迭代器与数组不同。要使用迭代器,必须使用foreach迭代它。

<?php
$path = "test.dir";
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($path)
);
$file_array = array();
foreach ($files as $f) {
    $file_array[] = $f;
}
print_r($file_array);

输出:

Array
(
    [0] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/.
            [fileName:SplFileInfo:private] => .
        )

    [1] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/..
            [fileName:SplFileInfo:private] => ..
        )

    [2] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub1/.
            [fileName:SplFileInfo:private] => .
        )

    [3] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub1/..
            [fileName:SplFileInfo:private] => ..
        )

    [4] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub1/filea.jpg
            [fileName:SplFileInfo:private] => filea.jpg
        )

    [5] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub1/fileb.jpg
            [fileName:SplFileInfo:private] => fileb.jpg
        )

    [6] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub2/.
            [fileName:SplFileInfo:private] => .
        )

    [7] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub2/..
            [fileName:SplFileInfo:private] => ..
        )

    [8] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub2/sub21/.
            [fileName:SplFileInfo:private] => .
        )

    [9] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub2/sub21/..
            [fileName:SplFileInfo:private] => ..
        )

    [10] => SplFileInfo Object
        (
            [pathName:SplFileInfo:private] => test.dir/sub2/sub21/filee.jpg
            [fileName:SplFileInfo:private] => filee.jpg
        )

)