在没有arsort的情况下正确排序数组

时间:2012-10-27 13:24:23

标签: php arrays sorting

我需要对具有以下形式的数组进行排序:

Array
(
    [18] => 9
    [14] => 4
    [53] => 9
    [10749] => 4
    [28] => 9
    [12] => 6
    [878] => 7
    [35] => 8
    [10769] => 1
    [9648] => 1
    [10751] => 1
    [27] => 1
    [80] => 3
)

arsort函数给了我:

Array
(
    [53] => 9
    [28] => 9
    [18] => 9
    [35] => 8
    [878] => 7
    [12] => 6
    [14] => 4
    [10749] => 4
    [80] => 3
    [27] => 1
    [10769] => 1
    [9648] => 1
    [10751] => 1
)

这很好,但问题是当价值相同时我希望按照keys对它们进行排序,这可能吗?所以我会得到:

Array
(
    [18] => 9
    [28] => 9
    [53] => 9
    [35] => 8
    [878] => 7
    [12] => 6
    [14] => 4
    [10749] => 4
    [80] => 3
    [27] => 1
    [9648] => 1
    [10751] => 1
    [10769] => 1
)

有人能告诉我怎么做吗?

2 个答案:

答案 0 :(得分:1)

这是使用php函数而不是非常慢的bubblesort

的解决方案

    

$arr = array(
    '18'    => 9,
    '14'    => 4,
    '53'    => 9,
    '10749' => 4,
    '28'    => 9,
    '12'    => 6,
    '878'   => 7,
    '35'    => 8,
    '10769' => 1,
    '9648'  => 1,
    '10751' => 1,
    '27'    => 1,
    '80'    => 3
    );

print_r($arr);

arsort( $arr );
print_r($arr);


$last = null;
$tmp = array();
$result = array();
foreach( $arr as $k => $v ) {
    if ( $last && $v != $last ) {
        krsort($tmp);

        foreach ( $tmp as $kt => $vt ) {
            $result[ $kt ] = $vt;
        }

        $tmp = array();
    }
    $tmp[$k] = $v;

    $last = $v;
}

krsort($tmp);

foreach ( $tmp as $kt => $vt ) {
    $result[ $kt ] = $vt;
}

print_r($result);

答案 1 :(得分:0)

你的意思是你不想使用

rsort( ) – Sorts a Scalar array in reverse order
arsort( ) - Sorts the Values in an Associative array in reverse order
krsort( ) - Sorts the Keys in an Associative array in reverse order

你可以尝试冒泡排序

function bubble_sort($arr) {
    $size = count($arr);
    for ($i=0; $i<$size; $i++) {
        for ($j=0; $j<$size-1-$i; $j++) {
            if ($arr[$j+1] > $arr[$j]) {
                swap($arr, $j, $j+1);
            }
        }
    }
    return $arr;
}

function swap(&$arr, $a, $b) {
    $tmp = $arr[$a];
    $arr[$a] = $arr[$b];
    $arr[$b] = $tmp;
}

 /* test bubble sort */


$arr = array(1,3,2,8,5,7,4,0);

print("Before sorting");
print_r($arr);

print("After sorting");
print_r(bubble_sort($arr));

  ?>