2013-04-08 159 views
4

我使用asort對簡單數組:排序數組由值,那麼關鍵

$arr = array('A'=>30, 'B'=>12, 'K'=>23, 'X'=>1, 'H'=>11, 'T'=>1, 'U'=1); 

asort($arr) 

產生

Array 
(
    [A] => 30 
    [K] => 23 
    [B] => 12 
    [H] => 11 
    [X] => 1 
    [T] => 1 
    [Z] => 1 
) 

是否存在被價值和一個鍵按本機方式調用(同時保留鍵/值關係)?

例如,我想我的結果落得這樣的:

Array 
(
    [A] => 30 
    [K] => 23 
    [B] => 12 
    [H] => 11 
    [T] => 1 
    [X] => 1 
    [Z] => 1 
) 

回答

0
<?php 
$arr = array('A'=>30, 'B'=>12, 'K'=>23, 'X'=>1, 'H'=>11, 'T'=>1, 'U'=>1); 

Function ArrSort ($Array){ 
    $tag = array(); 
    $num = array(); 

    foreach($Array as $key => $value){ 
     $tag[] = $key; 
     $num[] = $value; 
    } 
    array_multisort($num, SORT_DESC, $tag, SORT_ASC, $Array); 
    return $Array; 

} 

print_r(ArrSort($arr)); 
?> 

輸出:

Array 
(
    [A] => 30 
    [K] => 23 
    [B] => 12 
    [H] => 11 
    [T] => 1 
    [U] => 1 
    [X] => 1 
) 

組塊以上已被編輯成一個功能從位於這裏的原帖:PHP array multiple sort - by value then by key?

+0

再次檢查問題 - 我期待的結果與您的答案狀態不同。 – 2013-04-08 20:08:34

+0

現在修改代碼 – 2013-04-08 20:10:04

+0

我想我在這裏:http://stackoverflow.com/a/2282247/721073 – 2013-04-08 20:10:31