PHP Sorting Question
- Started
- Last post
- 11 Responses
- schjetne
So I have these lines, that make $file contain all the file names in a directory:
if ($dir = @opendir(".")) {
while (($file = readdir($dir)) !== false)Before I do anything else, I want to sort the files alphabetically. By default they are sorted by date created. I tried
sort ($file)
but that didn't seem to work. It say "wrong datatype" or something...
Any ideas?
Mike?
Anyone? Please?
- schjetne0
No one love me.
- schjetne0
And especially not with my english grammar skills. I need to start reading my posts before I post...
- mike0
if you put the items in an array, like the code I sent you, then you can sort or rsort them as you like...
:)
- enobrev0
i have a file sorting array that does the sorting correctly... I'll send it to ya if you're interested...
- unknown0
wow, 2 php-titans in one thread!
*staring amazed at screen*
you are lucky after all, schjetne!
- chl0
I think something like thil will do it for you...
if ($dir = @opendir(".")) {
while ($file[] = readdir($dir)) {}
}sort($file);
If it doesn't, email me directly and I'll try and help later tongiht.
- enobrev0
a regular sort will do the trick, but it is case sensitive. So if you have filenames that aren't all lower case, the sort won't be exact...
So you would need a sort function to surpass the case problem like:
function alphebetize ($a, $b) {
$sort_two[0] = strtoupper($a);
$sort_two[1] = strtoupper($b);
sort($sort_two);
return (strcmp (strtoupper ($sort_two[1]), strtoupper($b) ) ) ? 1 : -1;
}Then you set up your file array (pngs and jpgs only without the . and ..)
while ($file = readdir($handle))
if ($file != "." &&
$file != ".." &&
( ereg(".jpg",$file) ||
ereg(".png",$file) ) ) {$file_list[] = $file;
}
}and then use your alphabetize function:
usort($file_list, "alphebetize");
I have an example at http://photos.enobrev.com/
Let me know if you need the code.
- schjetne0
Mike, I'll find that old code and look at it once more. Thanks.
chl, that won't work, it was the first thing I tried.
enobrev, that looks interesting, I'll look into it.
- sevenfingers0
I usually take the "three V" route; "Vilja, Våld och Vaselin" I bet you'll figure it out with the above mentioned V's. You can thank me later.
- schjetne0
Wow sevenfingers, you truly opened my eyes.
I recommend everyone else to try the same approach. I use it on everything now, even my clients.
- sevenfingers0
and for you non-scandinavians, it translates pretty decently:
"Will, Violence and Vaseline"... yeah. that more like 4 V's.. oh well.