开发者

Sort array of strings with leading numbers followed by non-numeric characters

开发者 https://www.devze.com 2022-12-14 01:01 出处:网络
I can get a sorted filename list with the following code: $log_files = scandir(LLP_LOG_DIR)开发者_运维知识库;

I can get a sorted filename list with the following code:

$log_files = scandir(LLP_LOG_DIR)开发者_运维知识库;
$sorted = sort($log_files);

the filename format is X.log, where X is a progressive numeric value.

How can I solve the problem of getting

0.log
1.log
10.log
11.log
2.log
3.log

where the wanted result is

0.log
1.log
2.log
3.log
[..]
9.log
10.log
11.log
[..]

I can strip the ".log" string, sort them etc, but what is the most efficient way?


try natsort instead,

natsort($log_files)


Set the second parameter of sort to SORT_NUMERIC to have numeric sorting:

$sorted = $log_files;
sort($sorted, SORT_NUMERIC);

And note that sort sorts the array of the variable given with the first parameter. The return value of sort is just a boolean value.


Try natcasesort instead.

natcasesort($array);

because natsort is case sensitive.

0

精彩评论

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

关注公众号