3

Suppose I have an array like so:

    $array => Array
    (
        [5] => 0.33
        [3] => 1             
        [2] => 0.33
    )

When I do asort($array) I get:

    $array => Array
    (
        [5] => 0.33
        [2] => 0.33
        [3] => 1             
    )

How can I sort it so that first the values get sorted and if they have same value then the keys get sorted, so that my final output would be:

   $array => Array
    (
        [2] => 0.33
        [5] => 0.33
        [3] => 1             
    )
Undefined Variable
  • 4,196
  • 10
  • 40
  • 69

1 Answers1

5

You could try array_multisort with a little trick

$array = array(
    0 => 1,
    3 => 1,
    7 => 1,
    2 => 0.33,
    5 => 0.33,
    6 => 0.33,
    1 => 0.33,
);
$array_keys = array_keys($array);
array_multisort($array, $array_keys);
$result = array_combine($array_keys, $array);
var_dump($result);
sectus
  • 15,605
  • 5
  • 55
  • 97