Retrieving Subdirectories Using PHP
In PHP, you may encounter the need to access all subdirectories within a specific directory, excluding root and directory traversal indicators. Here's how you can achieve this using two different approaches.
Option 1: Utilizing glob()
The glob() function provides a straightforward way to list files and directories matching a specific pattern. To retrieve only subdirectories, use it with the GLOB_ONLYDIR option:
$subdirectories = glob('*/*', GLOB_ONLYDIR);
Option 2: Employing array_filter
array_filter allows you to filter an array based on a callback function. You can use it to identify subdirectories by excluding "." and ".." and filtering the glob() results:
function is_subdirectory($item) { return is_dir($item) && $item != '.' && $item != '..'; } $subdirectories = array_filter(glob('*'), 'is_subdirectory');
Usage in a Function
Once you have the array of subdirectories, you can pass it to a function for further processing. For instance, the following function prints the paths of all subdirectories:
function print_subdirectory_paths($subdirectories) { foreach ($subdirectories as $subdirectory) { echo $subdirectory . PHP_EOL; } }
위 내용은 루트 및 디렉터리 순회 표시기를 제외하고 PHP에서 하위 디렉터리를 검색하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!