search
HomeBackend DevelopmentPHP Tutorial帮忙看下这个递归文件夹函数哪里错了?

<code>function foreach_dir($filename,$dir){
    if(!is_dir($filename)) return;

    $r = opendir($filename);
    while($s = readdir($r)){
        if($s != '.' && $s != '..'){
            echo $s.'<br>';
            // $dir .= $s.'<br>';
            foreach_dir($filename.'/'.$s,$dir);
        }
        
    }
    return $dir;
}


echo foreach_dir('templates','');</code>

输出正确
default
images
index.html
top.jpg
menu
document.gif
documents.gif
index.html
sdocument.gif
sdocuments.gif
stylesheet.css
template.htm
subsilverlike

如果换成这样

<code>function foreach_dir($filename,$dir){
    // $dir = '';
    // echo $filename;
    if(!is_dir($filename)) return;

    $r = opendir($filename);
    while($s = readdir($r)){
        if($s != '.' && $s != '..'){
            // echo $s.'<br>';
            $dir .= $s.'<br>';
            foreach_dir($filename.'/'.$s,$dir);
        }
        
    }
    return $dir;
}


echo foreach_dir('templates','');</code>

输出
default
subsilverlike

我这是把 echo $s.'
';换成了$dir .= $s.'
';显示路径就不完全了,哪里错了?

回复内容:

<code>function foreach_dir($filename,$dir){
    if(!is_dir($filename)) return;

    $r = opendir($filename);
    while($s = readdir($r)){
        if($s != '.' && $s != '..'){
            echo $s.'<br>';
            // $dir .= $s.'<br>';
            foreach_dir($filename.'/'.$s,$dir);
        }
        
    }
    return $dir;
}


echo foreach_dir('templates','');</code>

输出正确
default
images
index.html
top.jpg
menu
document.gif
documents.gif
index.html
sdocument.gif
sdocuments.gif
stylesheet.css
template.htm
subsilverlike

如果换成这样

<code>function foreach_dir($filename,$dir){
    // $dir = '';
    // echo $filename;
    if(!is_dir($filename)) return;

    $r = opendir($filename);
    while($s = readdir($r)){
        if($s != '.' && $s != '..'){
            // echo $s.'<br>';
            $dir .= $s.'<br>';
            foreach_dir($filename.'/'.$s,$dir);
        }
        
    }
    return $dir;
}


echo foreach_dir('templates','');</code>

输出
default
subsilverlike

我这是把 echo $s.'
';换成了$dir .= $s.'
';显示路径就不完全了,哪里错了?

你熟读一下你程序的逻辑就知道了,虽然你在循环中把$dir传递到了foreach_dir中进行递归,但是你没有获取和处理foreach_dir返回的$dir,所以最后你得到的也就是根目录和其下一级文件,没有更进的目录了。

程序应该是这样的

<code>function foreach_dir($filename, $dir)
{
    if(!is_dir($filename)) return '';

    $r = opendir($filename);
    while ($s = readdir($r)) {
        if($s != '.' && $s != '..') {
            $dir .= $s.'<br>';
            $dir .= foreach_dir($filename . '/' . $s, $dir);
        }
        
    }
    return $dir;
}


echo foreach_dir('templates','');</code>

因为你把echo都注掉了,default和subsilverlike应该都是templates目录下的第一级子目录,是由语句$dir .= $s.'
'拼接出来了,实际上除了第一次调用函数外没有任何内容被打印,所以就是这个结果了。你可以把你的第二段代码的最后几句修改成:

<code>    echo $dir;
}
foreach_dir('templates','');</code>

应该就能看到更多结果了。

不过两段代码的逻辑都很不清楚,我写一段你看一下能明白不。

<code>$details = [];
function eachDir($dir, &$results) {
    if (! is_dir($dir)) return false; //不是目录就不需要处理了
    $hd = opendir($dir);
    while($file = readdir($hd)) {
        if ($file == '.' || $file == '..') continue; //忽略这两个目录
        $file = $dir . '/' . $file; //拼接完整的文件名或路径名
        $results[] = $file; //放到遍历结果中
        if (is_dir($file)) eachDir($file, $results); //如果是目录,递归处理
    }
    return true;
}
eachDir('templates', $details); //$details是通过传址的方式处理的
print_r($details);
/**
 * 我期望的输出类似
 * templates/default
 * templates/detault/images
 * ...
 */</code>

这个代码没测试。
不建议在函数中使用echo,就算是练习也一样,因为echo出来的东西就无法被继续处理了,所以应该尽量避免。同时echo也会影响你的思维方式,先处理再输出的时候,你的注意力可以集中在当前的步骤上,而边处理边输出相当于一心二用。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),