![](/img/trans.png)
[英]PHP function to read directory & collect filenames &subdirectory names into an array?
[英]Is there an easy way to read filenames in a directory and add to an array?
我有一个目录: Audio/
其中只有mp3文件。 我想自动创建指向这些文件的链接的过程。 有没有办法读取目录并将该目录中的文件名添加到数组?
如果我们可以做一个关联数组,并且密钥是文件名减去.mp3标签,那将会非常酷。
有任何想法吗?
详细说明:我实际上有几个Audio/
文件夹,每个文件夹包含不同事件的mp3。 正在从数据库中提取事件详细信息并填充表。 这就是我复制代码的原因,因为现在每个Audio/
文件夹中,我必须为下载链接定义文件名并定义mp3播放器的文件名。
谢谢! 这将大大简化我的代码,因为我现在一遍又一遍地重复大量的代码!
SPL方式是使用DirectoryIterator :
$files = array();
foreach (new DirectoryIterator('/path/to/files/') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$files[] = $fileInfo->getFilename();
}
为了完整性:你也可以使用glob :
$files = array_filter(glob('/path/to/files/*'), 'is_file');
这将返回所有文件(但不是文件夹),您可以根据需要进行调整。
要获取文件名(而不是具有完整路径的文件),只需添加:
$files = array_map('basename', $files);
是的:使用scandir()
。 如果您只想要没有扩展名的文件名,请在从scandir()
收到的数组中的每个元素上使用basename()
scandir()
。
这应该能够做你想要的:
// Read files
$files = scandir($dirName);
// Filter out non-files ('.' or '..')
$files = array_filter($files, 'is_file');
// Create associative array ('filename' => 'filename.mp3')
$files = array_combine(array_map('basename', $files), $files);
当然......我认为这应该有效......
$files[] = array();
$dir = opendir("/path/to/Audio") or die("Unable to open folder");
while ($file = readdir($dir)) {
$cleanfile = basename($file);
$files[$cleanfile] = $file;
}
closedir($dir);
我想这应该工作......
$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$results[] = $file;
}
}
closedir($handler);
这应该工作,如果你想从数组中排除任何文件,只需将它们添加到if语句,对于文件扩展名也是如此
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.