开发者

PHP: Sort an array

开发者 https://www.devze.com 2023-03-20 00:25 出处:网络
Please how do i sort the below array Array ( \'ben\' => 1.0, \'ken\' => 2.0, \'sam\' => 1.5 ) to 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

精彩评论

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