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

Member Avatar for diafol

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

$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;
        }
    }
}

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.

<?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);
?>
Member Avatar for diafol

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.