Jump to content

[SOLVED] sort() array function in ASC order?


EchoFool

Recommended Posts

Is there a way to get sort($array) to display values in DESC order rather than ASC order?

 

Because im trying to create a list of who is doing the best but the list is backwards ie the worst person is at the top which is wrong.... this is what i have:

 

<?php
// build array etc $states


sort($states);

foreach($states AS $StateID => $value){
$ID = $ID + 1; //avoid a query seeking ID 0
$Get = mysql_query("SELECT Name FROM mayor_state WHERE StateID='$StateID'")
Or die(mysql_error());
$row2 = mysql_fetch_assoc($Get);
?>
<tr>
    <td width="200" align="center"><?=$row2['Name']?></td>
    <td width="200" align="center"><?=number_format($value)?></td>
    </tr>
<?
}
?>
</table>

 

the result shows:

 

1

2

3

4

5

 

But im trying to get it to be :

 

5

4

3

2

1

 

Hope you can help.

Link to comment
https://forums.phpfreaks.com/topic/137696-solved-sort-array-function-in-asc-order/
Share on other sites

Hmm that sorts the value of the array but the first section... what i mean is:

 

[ 0 ] = 12

[1] = 15

with rsort it becomes:

 

[ 0 ] = 15

[1] = 12

 

 

basically i need the [ 0 ] and [1] to also sort with it if that makes sense?

 

so like:

 

[1] = 15

[ 0 ] =  0

 

How would i do that?

I did but i couldn't find the one i needed.

 

ksort just sorts in order of key. But i need it to sort by value of the key but when it sorts the values... also keep their key with it so :

 

[ 0 ] = 4

[1] = 23

[2] = 1

 

Becomes:

[1] = 23

[ 0 ] = 4

[2] = 1

 

I tried:

 

asort()

arsort()

ksort()

sort()

natsort()

rsort()

 

 

None of them seemed to do it though. :(

Ah, now that makes sense lol.

 

I am sure there is a function to do this somewhere...but this might work.

 

<?php
function keepKeySort($array) {
       $array2 = $array;
       sort($array);
       foreach ($array as $key => $val) {
             $newKey = array_search($val, $array2); 
             $returnArray[$newKey] = $val;
       }
       return $returnArray;
}
?>

 

Not sure if that will work, but if not maybe you can tweak it to work.

Try arsort() again. It is the one you want. If it did not work, post what it did do and post an example of your data. If your data is strings that contain numbers, you need to use SORT_NUMERIC as the second parameter.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.