How to have a stable sort in PHP with arsort()?

后端 未结 7 689
迷失自我
迷失自我 2020-12-03 22:40

i need to sort an array in php based on value, array use some numbers for keys and values, for example like this:

$a = array(70 => 1 ,82          


        
7条回答
  •  自闭症患者
    2020-12-03 23:21

    Simple solution with array_multisort.

    $assoc = [
        70 => 1,
        82 => 5,
        61 => 3,
        55 => 1,
        34 => 2,
        53 => 2,
        21 => 4,
        13 => 5,
    ];
    
    $keys = array_keys($assoc);
    array_multisort($assoc, SORT_DESC, range(1, count($assoc)), $keys);
    $assoc = array_combine($keys, $assoc);
    
    print_r($assoc);
    

提交回复
热议问题