PHP Get all subdirectories of a given directory

2019-01-02 17:59发布

How can I get all sub-directories of a given directory without files, .(current directory) or ..(parent directory) and then use each directory in a function?

16条回答
谁念西风独自凉
2楼-- · 2019-01-02 18:21

I have written a scanner that works very well and scans directories and subdirectories in each directory and files.

function scanner($path){
    $result = [];
    $scan = glob($path . '/*');
    foreach($scan as $item){
        if(is_dir($item))
            $result[basename($item)] = scanner($item);
        else
            $result[] = basename($item);
    }
    return $result;
}

Example

var_dump(scanner($path));

returns:

array(6) {
  ["about"]=>
  array(2) {
    ["factory"]=>
    array(0) {
    }
    ["persons"]=>
    array(0) {
    }
  }
  ["contact"]=>
  array(0) {
  }
  ["home"]=>
  array(1) {
    [0]=>
    string(5) "index.php"
  }
  ["projects"]=>
  array(0) {
  }
  ["researches"]=>
  array(0) {
  }
  [0]=>
  string(5) "index.php"
}
查看更多
旧人旧事旧时光
3楼-- · 2019-01-02 18:22

Proper way

/**
 * Get all of the directories within a given directory.
 *
 * @param  string  $directory
 * @return array
 */
function directories($directory)
{
    $glob = glob($directory . '/*');

    if($glob === false)
    {
        return array();
    }

    return array_filter($glob, function($dir) {
        return is_dir($dir);
    });
}

Inspired by Laravel

查看更多
荒废的爱情
4楼-- · 2019-01-02 18:23

Here is how you can retrieve only directories with GLOB:

$directories = glob($somePath . '/*' , GLOB_ONLYDIR);
查看更多
爱死公子算了
5楼-- · 2019-01-02 18:28

you can use glob() with GLOB_ONLYDIR option

or

$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
查看更多
登录 后发表回答