views:

53

answers:

2

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
File 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.

+4  A: 

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";
}
mqchen
+1 for solid 2 minutes work!
suicideducky
Thank you, this looks good. How about if the input is something like Test File 1Test File 2Or like:File 1 testFile 2 Test
Chaim Chaikin
+2  A: 

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"...

tvanfosson
This is exactly what I need. Thanks a lot.
Chaim Chaikin