Jake Badlands
Jake Badlands

Reputation: 1026

PHP : how to process the files _alphabetically_ using DirectoryIterator?

Using this way, after the completion of DirectoryIterator cycle
you will get a list of filenames, and later you will be able to alphabetically sort it,
so that you can process each file with a filename from this list - in alphabetical order...

Now, what if, after the completion of DirectoryIterator cycle,
you need an array (alphabetically sorted by filename), that contains not only the filename,
but also all the other file properties, such as:

The problem here is, you cant sort before the completion of DirectoryIterator cycle,
and after it you will not be able to access anything other than filenames from your list...

Upvotes: 1

Views: 2544

Answers (1)

Jake Badlands
Jake Badlands

Reputation: 1026

DirectoryIterator objects provide a simple way to access many of file properties.

$dir = new DirectoryIterator($path);
foreach ($dir as $fileInfo) {
    if ((!$fileInfo->isDot())&&($fileInfo->GetExtension() == "txt")) {
        /* You can access the file information inside this cycle */
        $octal_perms = substr(sprintf('%o', $fileInfo->getPerms()), -4);
        echo $fileInfo->getFilename() . " " . $octal_perms . "\n";
    }
}

If we need the fileInfo objects after the completion of DirectoryIterator cycle,
we will have to clone (copy) all these DirectoryIterator objects into a new array,
and then sort this array alphabetically by filename attribute of DirectoryIterator objects.

function cmp($a, $b)
{
    return strcmp($a->getFilename(), $b->getFilename());
}

$dir = new DirectoryIterator($path);
foreach ($dir as $fileInfo) {
    if ((!$fileInfo->isDot())&&($fileInfo->GetExtension() == "txt")) {
        /* we need to clone a fileInfo object into array, not just assign it */
        $allFilesInfo[] = clone $fileInfo;
    }
}

/* Alphabetically sorting the array with DirectoryIterator objects, by filename */
usort($allFilesInfo, 'cmp');

foreach ($allFilesInfo as $fileInfo) {
    /* Everything is alphabetical here ;) */
    $octal_perms = substr(sprintf('%o', $fileInfo->getPerms()), -4);
    echo $fileInfo->getFilename() . " " . $octal_perms . "\n";
}

^^ In this last cycle, you can work with your files in alphabetical order,
while being able to access all their properties :)

NOTE: in case of crash, caused by "too many open files" error,
increase the max limit of open file descriptors per a process in your OS.
Related config files are depend on your OS, and usually they're stored in /etc

Upvotes: 1

Related Questions