tags:

views:

68

answers:

1

The function below returns all folders in a given directory down to multiple levels.

I only need one level depth though, just folders in the target directory, no subfolders.

Also the function returns the full path to the folder, I only want the folder name. I'm sure I'm missing something simple.

How can I modify the function to return only the folder names of the given directory? (not the full paths to each folder)

$myArray = get_dirs('../wp-content/themes/mytheme/images');

<?php
  function get_dirs( $path = '.' ){
 return glob( 
   '{' . 
  $path . '/*,'    . # Current Dir
  $path . '/*/*,'  . # One Level Down
  $path . '/*/*/*' . # Two Levels Down, etc.
   '}', GLOB_BRACE + GLOB_ONLYDIR );
  }
?>

btw, thanks to Doug for the original function help!

+2  A: 

Instead of using glob(), I would suggest using the DirectoryIterator class.

function get_dirs($path = '.') {
    $dirs = array();

    foreach (new DirectoryIterator($path) as $file) {
        if ($file->isDir() && !$file->isDot()) {
            $dirs[] = $file->getFilename();
        }
    }

    return $dirs;
}
Jordan Ryan Moore
Hi Jordan, this looks great, but I'm having one issue. I'm running it from localhost but getting a fatal error...Fatal error: Uncaught exception 'UnexpectedValueException' with message 'DirectoryIterator::__construct(../wp-content/themes/mytheme/images) [<a href='directoryiterator.--construct'>directoryiterator.--construct</a>]: failed to open dir: No such file or directory' in C:\xampplite\htdocs\wordpress\wp-content\themes\mytheme\functions.php:436
Scott B
Here's my caller.$mydir = get_dirs('../wp-content/themes/mytheme/images');
Scott B
Try `$mydir = get_dirs(realpath('../wp-content/themes/mytheme/images'));` instead.
Jordan Ryan Moore
...or better yet: build and pass the absolute path to the function yourself. I don't know your structure, but this could be as simple as `$_SERVER['DOCUMENT_ROOT'] . '/wp-content/themes/mytheme/images'`.
Jordan Ryan Moore