我如何使用 PHP 列出按字母顺序排序的目录中的前 5 个文件或目录?
最佳答案
使用 scandir()
:
array_slice(array_filter(scandir('/path/to/dir/'), 'is_file'), 0, 5);
array_filter()
与 is_file()
函数回调确保我们只处理文件而无需编写循环,我们甚至不必关心关于 .
和 ..
因为它们是目录。
或者使用 glob()
- 它不会匹配像 .htaccess
这样的文件名:
array_slice(glob('/path/to/dir/*.*'), 0, 5);
或者使用 glob()
+ array_filter()
- 这个将匹配文件名,例如.htaccess
:
array_slice(array_filter(glob('/path/to/dir/*'), 'is_file'), 0, 5);
关于php - 如何使用 PHP 在目录中找到前 5 个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113565/