2

It's my 2D array:

$a = array(
    '6' => array(10, 5),
    '5' => array(20, 7),
    '40' => array(15, 9)
);

I can sort it simply with array_multisort:

foreach ($a as $k => $r) {
    $keys[$k] = $r[1]; 
}
array_multisort($keys, SORT_DESC, $a);

but it clears the keys ('6', '5', '40'):

Array
(
    [0] => Array
        (
            [0] => 15
            [1] => 9
        )

    [1] => Array
        (
            [0] => 20
            [1] => 7
        )

    [2] => Array
        (
            [0] => 10
            [1] => 5
        )

)

Does array_multisort have any parameters to keep array keys?

2
  • Do you want to sort the keys? Like 40, 6, 5 Commented Sep 12, 2012 at 10:13
  • 1
    @W.Kristianto: No, I want to sort the array. But I want to keep the keys also, and don't like to replace them by array numeric keys (start from 0) Commented Sep 12, 2012 at 10:25

1 Answer 1

7

Simpler solution using uasort:

uasort($a, function ($a, $b) { return $a[1] - $b[1]; });
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. but how can I change the sorting direction?
Switch the $a and $b arguments around.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.