简体   繁体   中英

How to check if a folder has sub folders using glob?

I have a dir TestRoot with two folder: TestFolderA, which has another folder and two files, and TestFolderB which only has one file. I am trying to check whether these folders themselves contain more folders.

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>

</head>

<body class="stretched">
<?php 
$root = "docs/RootTest"; 
$files = scandir($root);

 foreach($files as $file)
        {
            if ($file != '.' && $file != '..') 
            {
                $link = $root.'//'.$file;

                if(is_dir($link)) //Check if file is a folder
                {
                    $folders = glob($link."/", GLOB_ONLYDIR);
                    if(count($folders)>0)  //Check if it contains more folders
                    {
                        echo $link." ";
                        echo "Has Sub-folders ";
                    }                       
                    else
                    {
                        echo $link." ";
                        echo "None ";
                    }
                }
            }
        }   
?>  
</body>
</html>

When I run this code the output is "docs/RootTest//TestFolderA Has Sub-folders" which is correct however I also get the output "docs/RootTest//TestFolderB Has Sub-folders" which is not correct. What am I doing wrong?

$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);

You can also try glob() followed GLOB_ONLYDIR option

Change line

$folders = glob($link."/", GLOB_ONLYDIR);

to

$folders = glob($link."/*", GLOB_ONLYDIR);

Just added "*"

OK albeit not the way I wanted to, but after glob for some reason refuses to behave as expected II instead opted to just scan the directory again and sorted it so that folders are first in the array. Then I just checked if the first element is a directory.

            if(is_dir($link))
            {
                $folders = scandir($link, 1);
                if(is_dir($link.'/'.$folders[0]))
                {
                     echo $link." ";
                    echo "Has Sub-folders "; 
                }

PHP is_dir() Function

The is_dir() function checks whether the specified file is a directory.

This function returns TRUE if the directory exists.

<?php
$file = "images";
if(is_dir($file))
  {
  echo ("$file is a directory");
  }
else
  {
  echo ("$file is not a directory");
  }
?> 

Output :

images is a directory 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM