Re: Help with recursive function
| From: | Jim Lucas | Date: | Sat, 07 Feb 2015 01:01:02 +0000 |
| Subject: | Re: Help with recursive function | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-324412@lists.php.net to get a copy of this message | ||
On 02/05/2015 10:39 PM, Jeffry Killen wrote:
> Hello again;
>
> I am writing a recursive file system reading method
> (just for the challenge, i am re inventing a wheel)
>
> and I am only getting to the third level below the initial dir
> when I know there is five levels below.
>
> I don't see why:
>
> private function getDirList($_dir)
> {
> $_out = array();
> $_valid = '';
> $_DR = opendir($_dir);
> while($_x = readdir($_DR))
> {
> switch($_x)
> {
> case '.':
> case '..':
> break;
> default:
> if(is_dir($_x))
> {
> $_valid = self::screen($_dir.'/'.$_x, 'dir');
> if($_valid['error'])
> {
> self::$_readError[count(self::$_readError)] =
> $_valid['error'];
> continue;
> }
> else if($_valid['pass'])
> {
> self::$_dirsToRead[$_dir.'/'.$_x] = true;
> self::getDirList($_dir.'/'.$_x); ///<<<< this
> should accumulate directories, shouldn't it?
> }
> }
> else if(is_file)
> {
> continue;
> }
> break;
> }
> }
> closedir($_DR);
> }
>
> thank you for time and attention
> JK
>
Here is what I would do:
function get_directory_structure($path) {
$directories = array();
foreach ( glob($path.'/*', GLOB_ONLYDIR) AS $entry) {
$directories[] = $entry;
$directories += get_directory_structure($entry);
}
return $directories;
}
print_r(get_directory_structure('/path/to')); # no trailing /
--
Jim Lucas
http://www.cmsws.com/
http://www.cmsws.com/examples/