HugoMen'z
HugoMen'z

Reputation: 31

Sorting an Array properly without arsort

I need to sort an array that has this form :

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
)

The arsort function gives me :

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
)

That's good but the thing is that when values are the same I would like to get them sorted by their keys, is that possible ? so i would get :

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
)

Can anybody tell me how to do this?

Upvotes: 1

Views: 289

Answers (2)

NullPoiиteя
NullPoiиteя

Reputation: 57322

you mean you don't want to use

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

you can try bubble sort

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

  ?>

Upvotes: 0

bukart
bukart

Reputation: 4906

here's a solution using php functions instead of the very slow 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);

Upvotes: 1

Related Questions