Question

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?

Was it helpful?

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);

OTHER TIPS

You are only scanning one level deep and are not checking for the name of the folder/file. Instead, you'll need to scan recursively. Try something like this. I haven't tested this code - but you get the idea.

$directories = array();
get_directories('local', $directories);
print_r($directories);

function get_directories($path, &$directories)
{
    $dirs = scandir($path)
    foreach($dirs as $d)
    {
        if(is_dir("$path/$d")
        {
            if($d == 'model')
                $directories[] = "$path/$d";
            elseif($d != '.' && $d != '..')
                get_directories("$path/$d", $directories);
        }
    }
}

At the same time, if you don't need to do this in PHP, but just find all directories model, you can do this easily with shell command find:

$ find local/ -name model -type d

Here is another solution without recursion and which will work in php 4 as well as in php 5

<?php
$dir ='local';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
        $dir .= '/*';
        if (!$d) {
                $d =$dirs;
        } else {
                $d=array_merge($d,$dirs);
        }
}

$dir_to_match = 'models';

$result = array();
foreach ($d as $dir_name) {
        if (preg_match('#/' . $dir_to_match . '$#', $dir_name)) {
                $result[] = $dir_name;
        }
}
var_dump($result);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top