Is there an easy way to read filenames in a directory and add to an array?

回眸只為那壹抹淺笑 提交于 2019-12-23 16:34:39

问题


I have a directory: Audio/ and in that will be mp3 files only. I'm wanting to automate the process of creating links to those files. Is there a way to read a directory and add filenames within that directory to an array?

It'd be doubly cool if we could do an associative array, and have the key be the file name minus the .mp3 tag.

Any ideas?

To elaborate: I actual have several Audio/ folders and each folder contains mp3s of a different event. The event details are being pulled from a database and populating a table. That's why I'm duplicating code, because right now in each Audio/ folder, I'm having to define the filenames for the download links and define the filenames for the mp3 player.

Thank you! This will greatly simplify my code as right now I'm repeating tons of code over and over!


回答1:


The SPL way is with DirectoryIterator:

$files = array();
foreach (new DirectoryIterator('/path/to/files/') as $fileInfo) {
    if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
    $files[] = $fileInfo->getFilename();
}



回答2:


And for completeness : you could use glob as well :

$files = array_filter(glob('/path/to/files/*'), 'is_file'); 

This will return all files (but not the folders), you can adapt it as needed.

To get just the filenames (instead of files with complete path), just add :

$files = array_map('basename', $files);



回答3:


Yes: use scandir(). If you just want the name of the file without the extension, use basename() on each element in the array you received from scandir().




回答4:


This should be able to do what you're looking for:

// 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);



回答5:


Sure...I think this should work...

$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);

I imagine that should work...




回答6:


$results = array();
$handler = opendir($directory);
while ($file = readdir($handler)) {
  if ($file != "." && $file != "..") {
    $results[] = $file;
  }
}
closedir($handler);

this should work, if you want any files to be excluded from the array, just add them to the if statement, same for file extensions



来源:https://stackoverflow.com/questions/3509378/is-there-an-easy-way-to-read-filenames-in-a-directory-and-add-to-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!