Tim
Tim

Reputation: 13258

Sorting an array with uksort()

I have an array like this one:

$a = array("MA1" => 0, "MA10" => 1, "MA20" => 2, "MA5" => 3, "SM10" => 4, "SM8" => 5, "SM20" => 6, "SN33" => 7);

I want to sort it, that I will have the following order:

$a = array("MA1" => 0, "MA5" => 3, "MA10" => 1, "MA20" => 2, "SM8" => 5, "SM10" => 4, "SM20" => 6, "SN33" => 7);

So I need a order which is alphabetical within the first two chars and numeric of the rest. So I think I have to do this with

uksort($a, "cmp");

So I need a function like this:

function cmp($a, $b) {
    // ???
    return strcasecmp($a, $b);
}

How do I need to write the function so that the order will be right?

Thank you in advance & Best Regards.

Upvotes: 0

Views: 974

Answers (1)

leafnode
leafnode

Reputation: 1380

You can use built-in natural comparison function:

$a = array("MA1" => 0, "MA10" => 1, "MA20" => 2, "MA5" => 3, "SM10" => 4, "SM8" => 5, "SM20" => 6, "SN33" => 7);
uksort($a, "strnatcasecmp");
print_r($a);

The code above would produce following output:

Array
(
    [MA1] => 0
    [MA5] => 3
    [MA10] => 1
    [MA20] => 2
    [SM8] => 5
    [SM10] => 4
    [SM20] => 6
    [SN33] => 7
)

Upvotes: 3

Related Questions