PHP:从 readdir 到 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);
i wonder how i can transform exactly the following piece of code to scandir
instead of 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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
scandir
返回,引用:这意味着您将获得目录中文件的完整列表,然后可以使用带有
foreach
的自定义循环或某些过滤函数(例如array_filter
。Not tested, but I suppose something like this should to the trick :
基本上,这里:
scandir
获取文件列表array_filter
和自定义过滤函数过滤掉不需要的文件打乱
结果数组。scandir
returns, quoting :Which means you'll get the full list of files in a directory -- and can then filter those, using either a custom-made loop with
foreach
, or some filtering function likearray_filter
.Not tested, but I suppose something like this should to the trick :
Basically, here :
scandir
array_filter
and a custom filtering functionshuffle
the resulting array.不确定为什么要这样做,但这里有一个更简洁的解决方案:
Not sure why you want to do that, here's a much more concise solution though:
要开始解决此类问题,请务必查阅 PHP 手册并阅读注释,这总是非常有帮助的。它指出
scandir
返回一个数组,因此您可以使用foreach
。为了能够删除数组中的某些条目,这里有一个使用
for
的示例:另请参阅 SPL 迭代器 PHP 提供,特别是
RecursiveDirectoryIterator
和DirectoryIterator
。To get started with such problems always consult the PHP manual and read the comments, it's always very helpful. It states that
scandir
returns an array, so you can walk through it withforeach
.In order to be able to delete some entries of the array, here's an example with
for
:Also have a look at the SPL iterators PHP provides, especially
RecursiveDirectoryIterator
andDirectoryIterator
.这里有一个小功能可以扫描目录而不获取烦人的文件。
输出一个数组或 false,就像
scandir
一样Here's a little function to scan a directory without getting the annoying files.
Outputs an array or false just like
scandir
does