问题
Perhaps I'm doing something embarrassingly wrong, but why isn't this array being sorted?
$narray=array();
$dir_handle = @opendir($path.$projectFolder) or die("Unable to open $path$projectFolder");
$i=0;
while($file = readdir($dir_handle)) {
$filenameSplit = explode('.',$file);
if ($file != "." && $file != ".." && $filenameSplit[0] != "logo" && $filenameSplit[1] != "zip" && $filenameSplit[1] != "pdf" && $filenameSplit[1] != "doc" && $filenameSplit[1] != "psd" && $filenameSplit[1] != "") {
$narray[$i]=$file;
$i++;
}
}
natcasesort($narray);
I seem to be getting the same results I get when I don't attempt to sort the array at all. sort()
works, but nothing else seems to.
Thanks for any help!
Update:
Here are sample results:
With no sort:
03_piper_file-manager_02.jpg
05_piper_login-page_02.jpg
02_piper_file-manager_no-slides_01.jpg
04_piper_file-manager_02.jpg
01_piper_file-manager_no-slides_01.jpg
With sort()
:
01_piper_file-manager_no-slides_01.jpg
02_piper_file-manager_no-slides_01.jpg
03_piper_file-manager_02.jpg
04_piper_file-manager_02.jpg
05_piper_login-page_02.jpg
With natsort()
or natcasesort()
:
03_piper_file-manager_02.jpg
05_piper_login-page_02.jpg
02_piper_file-manager_no-slides_01.jpg
04_piper_file-manager_02.jpg
01_piper_file-manager_no-slides_01.jpg
I expect at the very least for natsort's results to look like sort's.
回答1:
natcasesort
maintains the key/value relationship, so if you are iterating over the array with an index, you will see this behavior.
Try print_r($narray)
after natcasesort
. You can iterate the array using foreach.
foreach ($narray as $elem)
{
/* operate on $elem */
}
来源:https://stackoverflow.com/questions/3398773/why-isnt-natsort-or-natcasesort-working-here