2

我想知道如何将以下代码完全转换为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);
4

4 回答 4

2

scandir返回,引用

成功时返回文件名数组,失败时返回 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');
}

基本上,这里:

  • 首先,您获取文件列表,使用scandir
  • 然后,你过滤掉你不想要的,使用array_filter自定义过滤功能
    • 注意:这个自定义过滤函数可以使用匿名函数编写,PHP >= 5.3
  • 最后,你shuffle得到了结果数组。
于 2010-07-13T10:14:34.853 回答
1

不知道你为什么要这样做,这里有一个更简洁的解决方案:

$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-13T10:12:17.777 回答
1

要开始解决此类问题,请始终查阅 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.

于 2010-07-13T10:18:05.380 回答
0

这是一个扫描目录而不获取烦人文件的小功能。

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;
}

scandir输出一个数组或 false 就像

于 2017-10-18T08:22:08.080 回答