Search code examples
phpphp-5.3scandir

Search and list specific directories only?


I want to search and list specific folders only and no matter how deep these folders are kept.

For instance, below is how I structure them,

local/
     app/
        master/
             models/
             views/
        slaves/
             models/
             views/
     scr/
     models/
     index.php

And I just want to list the folder of models into an array,

local/app/master/models/
local/app/slaves/models/
local/models/

My working code,

$directories = array();

$results = array_diff( scandir("local"), array(".", "..") );

foreach ($results as $result)
{
    if (is_dir("local/".$result)) {

        $directories[] = $result;
    }
}

var_dump($directories);

result,

array
  0 => string 'app' (length=3)
  1 => string 'models' (length=6)
  2 => string 'src' (length=3)

Any ideas?


Solution

  • // Create an object that allows us to iterate directories recursively
    // Stolen from here: 
    // http://www.php.net/manual/en/class.recursivedirectoryiterator.php#102587
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                              RecursiveIteratorIterator::CHILD_FIRST);
    
    // This will hold the result
    $result = array();
    
    // Loop the directory contents
    foreach ($iterator as $path) {
    
      // If object is a directory and matches the search term ('models')...
      if ($path->isDir() && $path->getBasename() === 'models') {
    
        // Add it to the result array
        $result[] = (string) $path;
    
      }
    
    }
    
    print_r($result);