Sorting list of files in an a multi dimensional array
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:
- file2.png
- file3.png
- file4.png
- file5.png
- file6.png
- file7.png
- file8.png
- file9.png
- file10.png
- file11.png
- 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.
精彩评论