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

后端 未结 7 722
迷失自我
迷失自我 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:25

    Construct a new array whose elements are the original array's keys, values, and also position:

    $temp = array();
    $i = 0;
    foreach ($array as $key => $value) {
      $temp[] = array($i, $key, $value);
      $i++;
    }
    

    Then sort using a user-defined order that takes the original position into account:

    uasort($temp, function($a, $b) {
     return $a[2] == $b[2] ? ($a[0] - $b[0]) : ($a[2] < $b[2] ? 1 : -1);
    });
    

    Finally, convert it back to the original associative array:

    $array = array();
    foreach ($temp as $val) {
      $array[$val[1]] = $val[2];
    }
    

提交回复
热议问题