2013-03-27 56 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"; 
} 
?>