PHP can be used.scandir()Function Sumis_dir()Use a function to retrieve all directories within a specified directory.
scandir()The function returns an array containing all files and directories in the specified directory.is_dir()This function determines whether a given path is a directory.
The following is an example code that uses these two functions to retrieve all directories within a specified directory:
<?php
// 指定要查找的目录
$dir = "/path/to/directory";
// 使用scandir()函数获取目录中的所有文件和目录
$files = scandir($dir);
// 遍历所有文件和目录,使用is_dir()函数判断是否是目录
foreach ($files as $file) {
if ($file != "." && $file != ".." && is_dir($dir . "/" . $file)) {
echo $file . "\n";
}
}
?>In the above code,$dirThe variable specifies the directory to search in. Use:scandir()The function retrieves all files and directories from the directory and then uses them.foreachIterate through each file and directory. For each file and directory, useis_dir()Check whether the given string represents a directory; if so, print the directory name. Note that to exclude the current directory (".") and the parent directory (".."), a conditional check should be added during the iteration.$file != "." && $file != ".."。
Encapsulate into a function
When you need to use the same code block multiple times, you can encapsulate it into a function so that you can call it whenever needed.
Here is an example code that encapsulates all directory listings from a specified directory into a single function:
function getDirectories($dir) {
$directories = array();
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != ".." && is_dir($dir . "/" . $file)) {
$directories[] = $file;
}
}
}
return $directories;
}In this function, we pass a single parameter.$dirThis parameter specifies the path to the directory to be searched. The function first creates an empty array.$directoriesUsed to store the found directory name. Then use it.is_dir()The function checks whether the incoming directory is a valid directory; if so, it is used.scandir()The function retrieves all files and directories within the specified directory. Then, use it.foreachIterate through each file and directory; use.is_dir()Check whether the function represents a directory; if so, add the directory name to the list.$directoriesWithin the array. Finally, the function returns.$directoriesAn array containing all the found directory names.
To call this function, simply pass the path to the directory you wish to search; for example:
$dir = "/path/to/directory";
$directories = getDirectories($dir);
print_r($directories);The above code will retrieve.$dirAll directories under the current directory, and store them in$directoriesUse the array.print_r()The function is printed out.