php遍历文件夹,查找文件

最近参加百度php实习生的两次面试,铺头盖脸的算法题,提笔一写就是十几分钟,当时还感觉八九不离十,回来写写运行下才知道问题多多。
这是其中两道被问到关于文件夹遍历的,分享一下:


1.给定一文件目录和一待查找的文件名,请设计算法返回该目录下所有该文件的路径。

    代码如下:

 
  
class File
{
    protected $arr = array();
    function findFile($flodername, $filename)
    {
        if (!is_dir($flodername)) {
            return "不是有效目录";
        }
        if ($fd = opendir($flodername)) {
            while($file = readdir($fd)) {
                if ($file != "." && $file != "..") {
                    $newPath = $flodername.'/'.$file;
                    if (is_dir($newPath)) {
                        $this->findFile($newPath, $filename);
                    }
                    if ($file == $filename) {
                        $this->arr[] = $newPath;
                    }
                }
            }
        }
        return $this->arr;
    }
}
php遍历文件夹,查找文件_第1张图片


2.给定一文件目录,请设计算法返回多维数组记录该目录下所有文件的路径。

     代码如下:
 
  
function listFile($flodername)
{
    if (!is_dir($flodername)) {
        return "不是有效目录";
    }
    if ($fd = opendir($flodername)) {
        while($file = readdir($fd)) {
            if ($file != "." && $file != "..") {
                $newPath = $flodername.'/'.$file;
                if (is_dir($newPath)) {
                    $arr[$file] = listFile($newPath);
                } else {
                    $arr[$file] = $newPath;
                }
            }
        }
    } else {
        return false;
    }
    return $arr;
}
php遍历文件夹,查找文件_第2张图片


方法多多,有问题可以一起讨论^_^

你可能感兴趣的:(PHP)