简体   繁体   中英

sort array by value then by key

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             
    )

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM