It seem that we I sort an array with files with different extensions, it groups the extensions together then sorts them. Example of a sort array a.gif z.gif b.png j.png Does anyone know how to do that?
There might be a better way, but this should work. function extension_sort(&$files) { $allfiles = array(); foreach ($files AS $file) { $extension = substr(strchr($file, '.'), 1); $allfiles['name'][] = basename($file, ".{$extension}"); $allfiles['extension'][] = $extension; } array_multisort($allfiles['extension'], $allfiles['name']); $files = array(); foreach ($allfiles['name'] AS $key => $name) { $files[] = "{$name}.{$allfiles[extension][$key]}"; } } PHP: Usage example $files = array('b.png', 'z.gif', 'j.png', 'a.gif'); extension_sort($files); print_r($files); /* Array ( [0] => a.gif [1] => z.gif [2] => b.png [3] => j.png ) */ PHP:
I think he wants it to sort by extension AND file name. If you have a better solution, feel free to share.
k... <?php $files = array('a.gif', 'j.png', 'z.gif', 'b.png'); usort($files, 'extSort'); // Sort files by extension, then name function extSort($first, $second) { // Match a filename, dot, and extension $pattern = '/^(.*)\.(.*?)?$/'; if (preg_match($pattern, $first, $firstSet) && preg_match($pattern, $second, $secondSet)) { list(, $firstName, $firstExt) = $firstSet; list(, $secondName, $secondExt) = $secondSet; // If the extensions are equal, sort by name if ($firstExt == $secondExt) { return strcmp($firstName, $secondName); } // Otherwise, sort by extension return strcmp($firstExt, $secondExt); } return 0; } ?> PHP: