开发者

Sorting list of files in an a multi dimensional array

开发者 https://www.devze.com 2023-04-13 07:31 出处:网络
There are many similar questions and I almost have the solution but I have a case that isn\'t sorted like the client wants it.

There are many similar questions and I almost have the solution but I have a case that isn't sorted like the client wants it.

I am using the following function to sort my array:

function sortFile开发者_Go百科sByName($a, $b) {
    if (basename(strtolower($a['path'])) == basename(strtolower($b['path']))) {
        return 0;
    }
    return (basename(strtolower($a['path'])) < basename(strtolower($b['path']))) ? -1 : 1;
}

The problem is that I get the following order when sorting my list:

  1. file2.png
  2. file3.png
  3. file4.png
  4. file5.png
  5. file6.png
  6. file7.png
  7. file8.png
  8. file9.png
  9. file10.png
  10. file11.png
  11. file1.png

The client would like to have file1.png at the top of the list and I have to say I'm a little confused as how to achieve that. Any help is appreciated :)

After the answers given I've gotten much closer, I changed my function to the following:

function sortFilesByName($a, $b) {
    return strnatcmp(strtolower(basename($a['path'])), strtolower(basename($b['path'])));
}

And it works! Thanks!


I think you need the natsort(); function instead. It sorts alphanumerically.

<?php 
   $numbers = array("1.gif","2.gif","20.gif","10.gif"); 
   natsort($numbers); 
   print_r($numbers); 
?> 

Outputs

Array
(
[0] => 1.gif
[1] => 2.gif
[3] => 10.gif
[2] => 20.gif
)


The natsort function will do what you want: http://php.net/manual/en/function.natsort.php.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号