1

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

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
)

谁能告诉我该怎么做?

4

2 回答 2

1

这是一个使用 php 函数而不是非常慢的冒泡排序的解决方案

    

$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);
于 2012-10-27T13:52:26.920 回答
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));

  ?>
于 2012-10-27T13:27:02.180 回答