doushi8599 2012-11-19 22:42
浏览 70
已采纳

PHP案例切换行为打破了递归scandir函数

during my quest for some basic php knowledge , I tried to do a simple function to read files and dirs that will not use recursive iterators. (more of an exercise but actually needed for any php<5.3 servers)

the function works great - but when i tried to add a switch ($output) - it no longer lists all the files (for example, before adding the switch, it can see 61 files in 4 folders (3+root) but with the added switch it can only see 47 (only root) . am I doing something wrong here ? why does the switch statement break the faux "recursive-nest" ??

    function o99_list_my_files_scandir($dir,$output) 
    { 

        $result = $result2 = array(); 

        $root = scandir($dir); 

        foreach($root as $value) 
        { 

          if($value === '.' || $value === '..' || $value == 'Thumb.db' || $value == 'Thumbs.db' || $value == '') { continue;} 

            if(is_file("$dir/$value")) {$result[]="$dir/$value"; continue;} // array files
            if(is_dir("$dir/$value")) {$result2[]="$dir/$value"; continue;} // array dirs

            foreach(o99_list_my_files_scandir("$dir/$value") as $value) 

            { 
                $result[] = $value; 
            }
        } 
            // this is the troublemaker ...

            switch ($output) {
                case 'dirs' :
                return array_filter($result2);  // clean empty results of dirs
                break;

                case 'files' :
                return array_filter($result);   // Clean empty array of files
                break; 
            }

} 

is there any other simple way to get the function to return separate lists of dirs AND files and not a unified array ?

  • 写回答

2条回答 默认 最新

  • doudou0612 2012-11-19 22:50
    关注

    Because in this line...

    foreach(o99_list_my_files_scandir("$dir/$value") as $value)
    

    ...you don't give $output to the recursively called function, so it won't output anything. Change it to:

    foreach(o99_list_my_files_scandir("$dir/$value", $output) as $value)
    

    Actually you should have gotten a warning about the missing argument.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题