[英]PHP: readdir to scandir?
我想知道如何将下面的代码准确地转换为scandir
而不是readdir
?
$path = 'files';
//shuffle files
$count = 0;
if ($handle = opendir($path)) {
$retval = array();
while (false !== ($file = readdir($handle))) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if ($file != '.' && $file != '..' && $file != '.DS_Store' &&
$file != 'Thumbs.db') {
$retval[$count] = $file;
$count = $count + 1;
} else {
//no proper file
}
}
closedir($handle);
}
shuffle($retval);
scandir
返回, 引用 :
如果成功,则返回文件名数组;如果失败,则返回FALSE。
这意味着您将获得目录中文件的完整列表-然后可以使用带有foreach
的自定义循环或某些过滤功能(例如array_filter
过滤array_filter
。
未经测试,但我想这样的事情应该可以解决:
$path = 'files';
if (($retval = scandir($path)) !== false) {
$retval = array_filter($retval, 'filter_files');
shuffle($retval);
}
function filter_files($file) {
return ($file != '.' && $file != '..' && $file != '.DS_Store' && $file != 'Thumbs.db');
}
基本上,在这里:
scandir
获取文件列表 array_filter
和自定义过滤功能过滤掉不需要的数据
shuffle
。 不确定为什么要这样做,但是这里有一个更简洁的解决方案:
$path = 'files';
$files = array();
foreach (new DirectoryIterator($path) as $fileInfo) {
if($fileInfo->isDot() || $fileInfo->getFilename() == 'Thumbs.db') continue;
$files[] = $fileInfo->getFilename();
}
shuffle($files);
要开始解决此类问题,请始终查阅PHP手册并阅读注释,它总是非常有帮助的。 它指出scandir
返回一个数组,因此您可以使用foreach
它。
为了能够删除数组的某些条目,下面是带有for
的示例:
$exclude = array( ".", "..", ".DS_Store", "Thumbs.db" );
if( ($dir = scandir($path)) !== false ) {
for( $i=0; $i<count($dir); $i++ ) {
if( in_array($dir[$i], $exclude) )
unset( $dir[$i] );
}
}
$retval = array_values( $dir );
还可以查看PHP提供的SPL迭代器 ,尤其是RecursiveDirectoryIterator
和DirectoryIterator
。
这是一个扫描目录的小功能,无需获取烦人的文件。
function cleanscandir ($dir) {
$list = [];
$junk = array('.', '..', 'Thumbs.db', '.DS_Store');
if (($rawList = scandir($dir)) !== false) {
foreach (array_diff($rawList, $junk) as $value) {
$list[] = $value;
}
return $list;
}
return false;
}
输出数组或false,就像scandir
一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.