douzhao6584 2016-08-09 10:01
浏览 35

递归列出目录中的所有文件

I have the following function:

function listFiles($dir, $results = array()){       
    $entities = is_dir($dir) ? array_values(array_diff(scandir($dir), array('..', '.'))) : false ;  
    if( $entities )
        foreach( $entities as $e ) {
            $path = $dir.'/'.$e;
            if( is_dir($path) ) {
                listFiles($path, $results);
            }   
            $results[] = $path;
        }
        return $results;
    }
print_r(listFiles('/home/apps/public_html/test_folder'));

Although this works somehow the array has only the first branch of the directory. But if I echo the path inside foreach I get the path of every file from all folders and subfolders and so on.

Probably this is something very small but I can't figure out what and I could use some help. Thank you.

  • 写回答

1条回答 默认 最新

  • dongmibeng5885 2016-08-09 10:14
    关注

    inside your recursive function if a subdir is found you call the function itself with the subdir but it's results are not handled, not assigned to any variable so they are lost, you should push it to your results like this:

    if( is_dir($path) ){
        $results[] = listFiles($path, $results);
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度