Why isn't natsort (or natcasesort) working here?

时光总嘲笑我的痴心妄想 提交于 2020-01-03 19:40:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!