0

Hi,

I have an array with keys like this:
"9.345"
"16.765"
"8.123"
"0"
"0.123"

How do i sorth them, so the keys looks like this (numerically, descending order):
"16.765"
"9.345"
"8.123"
"0.123"
"0"

Thanks

5
Contributors
6
Replies
7
Views
5 Years
Discussion Span
Last Post by diafol
0

How are you using these arrays? Seems like very odd keys. Shouldn't they be values?

0
$len = $array.length();
for($i=0;$i<$len;$i++)
{
    for($j=$i+1;$j<$len-1;$j++)
    {
        if($array[$i]<$array[$j])
        {
        //shift
            $temp = $array[i];
            $array[i]=$array[j];
            $array[j]=$temp;
        }
    }
}
0

Then it gives me result like this:
"9.xx"
"8.xx"
"1.xx"
"16.xx"

Seems to be sorting as a string, need to sotrt as a number.

0
<?php
$array = array("16.765"=>'1',
        "4.345"=>'2',
        "17.123"=>'3',
        "23.123"=>'4',
        "6.111"=>'5',
        "6.113"=>'6',
        "6.112"=>'7',
        "17.3"=>'8',
        "0"=>'9');
$array2 = array();
foreach($array as $k=>$v){
    $array2[] = $k;
}
arsort($array2,SORT_NUMERIC);
$array3 = array();
foreach($array2 as $v){
    $array3[$v] = $array[$v];
}
var_dump($array3);
?>

Actually just tried ksort and array_reverse as metioned above and is much simpler:

<?php
$array = array("16.765"=>'1',
        "4.345"=>'2',
        "17.123"=>'3',
        "23.123"=>'4',
        "6.111"=>'5',
        "6.113"=>'6',
        "6.112"=>'7',
        "17.3"=>'8',
        "0"=>'9');

ksort($array,SORT_NUMERIC);
$array = array_reverse($array,true);
var_dump($array);
?>

Edited by Biiim

0

Just out of interest, what is this array for? Can't remember ever having seen keys like this before.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.