我想知道如何才能准确地将下面这段代码转换为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);发布于 2010-07-13 18:14:35
scandir返回,quoting:
如果成功,
将返回文件名数组;如果失败,则返回FALSE。
这意味着您将获得目录中文件的完整列表--然后可以使用带有foreach的定制循环或像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');
}基本上,这里:
PHP首先获取文件列表,使用scandir
array_filter和自定义过滤函数
shuffle操作。发布于 2010-07-13 18:12:18
不知道为什么要这样做,但这里有一个更简洁的解决方案:
$path = 'files';
$files = array();
foreach (new DirectoryIterator($path) as $fileInfo) {
if($fileInfo->isDot() || $fileInfo->getFilename() == 'Thumbs.db') continue;
$files[] = $fileInfo->getFilename();
}
shuffle($files);发布于 2010-07-13 18:18:05
要开始解决这类问题,请参考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 );还可以看看SPL iterators提供的代码,特别是RecursiveDirectoryIterator和DirectoryIterator。
https://stackoverflow.com/questions/3236038
复制相似问题