开发者

PHP: Sort an array

Please how do i sort the below array

Array
(
    'ben' => 1.0,
    'ken' => 2.0,
    'sam' => 1.5
)

to

Array
(
    'ken' => 2.0开发者_JAVA百科,
    'sam' => 1.5,
    'ben' => 1.0
)

Thanks.


try this.

<?php
$my_array = array('ben' => 1.0, 'ken' => 2.0, 'sam' => 1.5);

arsort($my_array);
print_r($my_array);
?>

The arsort() function sorts an array by the values in reverse order. The values keep their original keys.


http://www.php.net/manual/en/function.rsort.php


There's a whole manual section dedicated to such things:

http://php.net/manual/en/array.sorting.php

edit: specifically, arsort()


$arr = Array(
'ben' => 1.0,
'ken' => 2.0,
'sam' => 1.5
)    
$sorted = asort($arr);
$reversed = rsort($sorted);


If you use regular PHP array sorting functions, you'll lose your array keys. I think the shortest path to what you want is something like this:

$array = array("ben" => "1.0", "ken" => "2.0", "sam" => "1.5");
array_multisort($array, SORT_DESC);
print_r($array);

Make sure that all of your array values are either strings or numbers, otherwise the result will be unpredictable.


UPDATE: didnt notice you wanted it in revers.. int hat case use rsort

The sort function should work:

sort($theArray, SORT_NUMERIC);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜