开发者

Order by text and then by number

I have data like:

Audio 1 Test

File 10

Audio 2

Audio 3

File 11 Audio 1

Audio 13

Audio 22

File 20 Test

Test File 22

Audio 10

File 1

File 2

I need it order first by the text (i.e. Audio, File, Test) and then by number (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22 etc.)

The problem is that sorting it returns something like this:

Audio 1

Audio 1 Test

Audio 10

Audio 13

Audio 2

Audio 22

Audio 3

File 1

File 10

File 11

File 2

File 20 Test

Test File 22

While the result I want is:

Audio 1

Audio 1 Test

Audio 2

Audio 3

Audio 10

Audio 13

Audio 22

File 1

File 2

File 10

Fil开发者_运维问答e 11

File 20 Test

Test File 22

If they were just numbers (i.e. without the audio, file, test) then I could just sort numerically.

However, how can I sort here first by text and then by number.


The best solution would be to have a stable-sorting algorithm which would sort first by text and then by numbers, but you can achieve the same thing for this situation with usort and your own compare algorithm.

Here's a solution I did for you in 2 min (so apologies for ugly code).

<?php

$str = 'Audio 1
File 10
Audio 2
Audio 3
File 11
Audio 13
Audio 22
File 20
Test 22
Audio 10
File 1
File 2';

$arr = explode("\n", $str);

foreach($arr as $k => $v) {
    $arr[$k] = explode(" ", $v);
}

function mycmp($value1, $value2) {
    $txt1 = $value1[0];
    $txt2 = $value2[0];
    $num1 = intval($value1[1]);
    $num2 = intval($value2[1]);

    if($txt1 === $txt2) {
        return $num1 > $num2;
    }
    else {
        return strcmp($txt1, $txt2) > 0;
    }
};


usort($arr, "mycmp");

foreach($arr as $v) {
    echo $v[0]. "\t" . $v[1]. "\n";
}


I think what you are looking for is natsort.

bool natsort ( array &$array )

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering"...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜