PHP 中目录树的递归

发布于 2024-08-26 23:28:35 字数 649 浏览 3 评论 0原文

我有一组深度至少为 4 或 5 层的文件夹。我希望尽可能深入地递归目录树,并迭代每个文件。我已经获得了进入第一组子目录的代码,但没有更深入,我不知道为什么。有什么想法吗?

$count = 0;
$dir = "/Applications/MAMP/htdocs/site.com";
function recurseDirs($main, $count){
    $dir = "/Applications/MAMP/htdocs/site.com";
    $dirHandle = opendir($main);
    echo "here";
    while($file = readdir($dirHandle)){
        if(is_dir($file) && $file != '.' && $file != '..'){
            echo "isdir";
            recurseDirs($file);
        }
        else{
            $count++;
            echo "$count: filename: $file in $dir/$main \n<br />";
        }
    }
}
recurseDirs($dir, $count);

I have a set of folders that has a depth of at least 4 or 5 levels. I'm looking to recurse through the directory tree as deep as it goes, and iterate over every file. I've gotten the code to go down into the first sets of subdirectories, but no deeper, and I'm not sure why. Any ideas?

$count = 0;
$dir = "/Applications/MAMP/htdocs/site.com";
function recurseDirs($main, $count){
    $dir = "/Applications/MAMP/htdocs/site.com";
    $dirHandle = opendir($main);
    echo "here";
    while($file = readdir($dirHandle)){
        if(is_dir($file) && $file != '.' && $file != '..'){
            echo "isdir";
            recurseDirs($file);
        }
        else{
            $count++;
            echo "$count: filename: $file in $dir/$main \n<br />";
        }
    }
}
recurseDirs($dir, $count);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

千里故人稀 2024-09-02 23:28:35

查看新的 RecursiveDirectoryIterator

它仍然远非完美,因为您无法对搜索结果和其他内容进行排序,但仅获取文件列表就可以了。

手册中有一些简单的示例可以帮助您入门,如下所示:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), 
RecursiveIteratorIterator::SELF_FIRST);

foreach($objects as $name => $object){
    echo "$name\n";
}

?>

Check out the new RecursiveDirectoryIterator.

It's still far from perfect as you can't order the search results and other things, but to simply get a list of files, it's fine.

There are simple examples to get you started in the manual like this one:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), 
RecursiveIteratorIterator::SELF_FIRST);

foreach($objects as $name => $object){
    echo "$name\n";
}

?>
独﹏钓一江月 2024-09-02 23:28:35

调用中有一个错误

recurseDirs($file);

is_dir($file)

您必须给出完整路径:

recurseDirs($main . '/' .$file, $count);

但是

is_dir($main . '/' .$file)

,像其他答案一样,我建议使用 RecursiveDirectoryIteretor

There is an error in the call

recurseDirs($file);

and in

is_dir($file)

you have to give the full path:

recurseDirs($main . '/' .$file, $count);

and

is_dir($main . '/' .$file)

However, like other anwerers, I suggest to use RecursiveDirectoryIteretor.

很酷又爱笑 2024-09-02 23:28:35

对 is_dir 和 recurseDirs 的调用并不完全正确。另外,您的计数工作不正确。这对我有用:

$dir = "/usr/";
function recurseDirs($main, $count=0){
    $dirHandle = opendir($main);
    while($file = readdir($dirHandle)){
        if(is_dir($main.$file."/") && $file != '.' && $file != '..'){
            echo "Directory {$file}: <br />";
            $count = recurseDirs($main.$file."/",$count); // Correct call and fixed counting
        }
        else{
            $count++;
            echo "$count: filename: $file in $main \n<br />";
        }
    }
    return $count;
}
$number_of_files = recurseDirs($dir);

请注意对上面函数的调用的更改以及该函数的新返回值。

The call to is_dir and recurseDirs is not fully correct. Also your counting didn't work correctly. This works for me:

$dir = "/usr/";
function recurseDirs($main, $count=0){
    $dirHandle = opendir($main);
    while($file = readdir($dirHandle)){
        if(is_dir($main.$file."/") && $file != '.' && $file != '..'){
            echo "Directory {$file}: <br />";
            $count = recurseDirs($main.$file."/",$count); // Correct call and fixed counting
        }
        else{
            $count++;
            echo "$count: filename: $file in $main \n<br />";
        }
    }
    return $count;
}
$number_of_files = recurseDirs($dir);

Notice the changed calls to the function above and the new return value of the function.

旧伤慢歌 2024-09-02 23:28:35

所以是的:今天我很懒,在谷歌上搜索了一个递归目录列表的千篇一律的解决方案,然后发现了这个。当我最终编写了自己的函数时(至于为什么我什至花时间去谷歌,因为这超出了我的范围 - 我似乎总是觉得有必要重新发明轮子,没有合适的理由)我倾向于分享我的看法关于这一点。

虽然有支持和反对使用 RecursiveDirectoryIterator 的观点,但我将简单地发布我对简单递归目录函数的看法,并避免插话 RecursiveDirectoryIterator 的政治。

如下:

function recursiveDirectoryList( $root )
{

    /* 
     * this next conditional isn't required for the code to function, but I
     * did not want double directory separators in the resulting array values 
     * if a trailing directory separator was provided in the root path;
     * this seemed an efficient manner to remedy said problem easily...
     */
    if( substr( $root, -1 ) === DIRECTORY_SEPARATOR )
    {
        $root = substr( $root, 0, strlen( $root ) - 1 );
    }

    if( ! is_dir( $root ) ) return array();

    $files = array();
    $dir_handle = opendir( $root );

    while( ( $entry = readdir( $dir_handle ) ) !== false )
    {

        if( $entry === '.' || $entry === '..' ) continue;

        if( is_dir( $root . DIRECTORY_SEPARATOR . $entry ) )
        {
            $sub_files = recursiveDirectoryList( 
                $root . 
                DIRECTORY_SEPARATOR . 
                $entry . 
                DIRECTORY_SEPARATOR 
            );
            $files = array_merge( $files, $sub_files );
        }
        else
        {
            $files[] = $root . DIRECTORY_SEPARATOR . $entry;
        }
    }

    return (array) $files;

}

使用此函数,获取文件计数的答案很简单:

$dirpath = '/your/directory/path/goes/here/';

$files = recursiveDirectoryList( $dirpath );

$number_of_files = sizeof( $files );

但是,如果您不想要各个文件路径的数组的开销 - 或者根本不需要它 - 则不需要按照建议将计数传递给递归函数。

人们可以简单地修改我的原始函数来执行计数:

function recursiveDirectoryListC( $root )
{

    $count = 0;

    if( ! is_dir( $root ) ) return (int) $count;

    $dir_handle = opendir( $root );

    while( ( $entry = readdir( $dir_handle ) ) !== false )
    {

        if( $entry === '.' || $entry === '..' ) continue;

        if( is_dir( $root . DIRECTORY_SEPARATOR . $entry ) )
        {
            $count += recursiveDirectoryListC(
                $root .
                DIRECTORY_SEPARATOR .
                $entry .
                DIRECTORY_SEPARATOR
            );
        }
        else
        {
            $count++;
        }

    }

    return (int) $count;

}

在这两个函数中,如果目录不可读或发生其他错误,opendir() 函数实际上应该包含在条件中。确保正确执行此操作:

if( ( $dir_handle = opendir( $dir ) ) !== false ) 
{ 
    /* perform directory read logic */ 
}
else
{
    /* do something on failure */
}

希望这对某人有帮助......

So yeah: Today I was being lazy and Googled for a cookie cutter solution to a recursive directory listing and came across this. As I ended up writing my own function (as to why I even spent the time to Google for this is beyond me - I always seem to feel the need to re-invent the wheel for no suitable reason) I felt inclined to share my take on this.

While there are opinions for and against the use of RecursiveDirectoryIterator, I'll simply post my take on a simple recursive directory function and avoid the politics of chiming in on RecursiveDirectoryIterator.

Here it is:

function recursiveDirectoryList( $root )
{

    /* 
     * this next conditional isn't required for the code to function, but I
     * did not want double directory separators in the resulting array values 
     * if a trailing directory separator was provided in the root path;
     * this seemed an efficient manner to remedy said problem easily...
     */
    if( substr( $root, -1 ) === DIRECTORY_SEPARATOR )
    {
        $root = substr( $root, 0, strlen( $root ) - 1 );
    }

    if( ! is_dir( $root ) ) return array();

    $files = array();
    $dir_handle = opendir( $root );

    while( ( $entry = readdir( $dir_handle ) ) !== false )
    {

        if( $entry === '.' || $entry === '..' ) continue;

        if( is_dir( $root . DIRECTORY_SEPARATOR . $entry ) )
        {
            $sub_files = recursiveDirectoryList( 
                $root . 
                DIRECTORY_SEPARATOR . 
                $entry . 
                DIRECTORY_SEPARATOR 
            );
            $files = array_merge( $files, $sub_files );
        }
        else
        {
            $files[] = $root . DIRECTORY_SEPARATOR . $entry;
        }
    }

    return (array) $files;

}

With this function, the answer as to obtaining a file count is simple:

$dirpath = '/your/directory/path/goes/here/';

$files = recursiveDirectoryList( $dirpath );

$number_of_files = sizeof( $files );

But, if you don't want the overhead of an array of the respective file paths - or simply don't need it - there is no need to pass a count to the recursive function as was recommended.

One could simple amend my original function to perform the counting as such:

function recursiveDirectoryListC( $root )
{

    $count = 0;

    if( ! is_dir( $root ) ) return (int) $count;

    $dir_handle = opendir( $root );

    while( ( $entry = readdir( $dir_handle ) ) !== false )
    {

        if( $entry === '.' || $entry === '..' ) continue;

        if( is_dir( $root . DIRECTORY_SEPARATOR . $entry ) )
        {
            $count += recursiveDirectoryListC(
                $root .
                DIRECTORY_SEPARATOR .
                $entry .
                DIRECTORY_SEPARATOR
            );
        }
        else
        {
            $count++;
        }

    }

    return (int) $count;

}

In both of these functions the opendir() function should really be wrapped in a conditional in the event that the directory is not readable or another error occurs. Make sure to do so correctly:

if( ( $dir_handle = opendir( $dir ) ) !== false ) 
{ 
    /* perform directory read logic */ 
}
else
{
    /* do something on failure */
}

Hope this helps someone...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文