php scandir 只显示文件夹,不显示文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18705590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scandir to only show folders, not files
提问by user2574794
I have a bit of PHP used to pulled a list of files from my image directory - it's used in a form to select where an uploaded image will be saved. Below is the code:
我有一些 PHP 用于从我的图像目录中提取文件列表 - 它在表单中用于选择将保存上传的图像的位置。下面是代码:
$files = array_map("htmlspecialchars", scandir("../images"));
foreach ($files as $file) {
$filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file );
}
It works fine but shows all files and folders in 'images', does someone know a way to modify this code so that it only shows folder names found in the 'images' folder, not any other files.
它工作正常,但显示“图像”中的所有文件和文件夹,有人知道修改此代码的方法,以便它只显示“图像”文件夹中的文件夹名称,而不显示任何其他文件。
Thanks
谢谢
回答by dev-null-dweller
回答by Charaf JRA
Function is_dir()
is the solution :
函数is_dir()
是解决方案:
foreach ($files as $file) {
if(is_dir($file) and $file != "." && $file != "..") $filelist .= sprintf('<option value="%s">%s</option>' . PHP_EOL, $file, $file );
}
回答by Ryan Flynn
The is_dir()function requires an absolute path to the item that it is checking.
该is_dir()函数要求它正在检查该项目的绝对路径。
$base_dir = get_home_path() . '/downloads';
//get_home_path() is a wordpress function
$sub_dirs = array();
$dir_to_check = scandir($dir);
foreach ($dir_to_check as $item){
if ($item != '..' && $item != '.' && is_dir($base_dir . "/" . $item)){
array_push($sub_dirs, $item);
}
}
回答by Nebulosar
You could just use your array_map
function combined with glob
您可以将您的array_map
功能与glob
$folders = array_map(function($dir) {
return basename($dir);
}, glob('../images/*', GLOB_ONLYDIR));
Yes, I copied a part of it of dev-null-dweller, but I find my solution a bit more re-useable.
是的,我复制了dev-null-dweller 的一部分,但我发现我的解决方案更易于重用。