View Full Version : PHP sort()
darkblade
Mar 2nd 2007, 12:15 am
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?
nico_swd
Mar 2nd 2007, 12:37 am
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]}";
}
}
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
)
*/
bobby9101
Mar 2nd 2007, 8:05 am
wouldn't it be better to have it in a two-dimensional array and sort it by extension that way?
nico_swd
Mar 2nd 2007, 8:50 am
I think he wants it to sort by extension AND file name.
If you have a better solution, feel free to share. :)
Robert Plank
Mar 9th 2007, 3:39 pm
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;
}
?>
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.