2013-03-27 54 views
-1

如何排序下面的數組,因此頂部和鍵的較大值不會更改。排序數組而不更改密鑰

Array 
(
    [8] => 2 
    [9] => 2 
    [10] => 1 
    [12] => 1 
    [16] => 1 
    [17] => 1 
    [18] => 1 
    [19] => 1 
    [20] => 2 
    [23] => 1 
    [24] => 2 
    [25] => 2 
    [27] => 1 
    [50] => 2 
    [4] => 1 
    [14] => 1 
) 

感謝

+0

降臨時,你可以發表到目前爲止你已經嘗試了代碼? – 2013-03-27 16:48:39

+1

['asort()'](http://www.php.net/manual/en/function.asort.php)不起作用嗎? – nickb 2013-03-27 16:50:36

+0

@nickb - 根據他想要的順序需要使用'arsort'。 – Daedalus 2013-03-27 16:56:08

回答

0

您應該能夠使用asort/arsort。從PHP.net(http://www.php.net/manual/en/function.arsort.php)的arsort用法示例:

<?php 
    $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); 
    arsort($fruits); 
    foreach ($fruits as $key => $val) { 
     echo "$key = $val\n"; 
    } 
?> 
+0

這工作完美,非常感謝 – rob 2013-03-27 16:53:21

+0

@rob - 沒問題。 – Daedalus 2013-03-27 16:53:38

0

直接從PHP Manual

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

<?php 
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); 
asort($fruits); 
foreach ($fruits as $key => $val) { 
    echo "$key = $val\n"; 
} 
?>