如何订购数组而非字母PHP

时间:2014-01-30 11:31:41

标签: php arrays sorting

我想订购一个数组,但不是按字母顺序排列,我有这个:

Array(
'D' => 40
'S' => 60
'C' => 50
'I' => 60
)

它必须按降序排序:

Array(
 'S' => 60
 'I' => 60
 'C' => 50
 'D' => 40
)

但如果有重复值,则订单必须类似于D > I > S > C

Array(
 'I' => 60
 'S' => 60
 'C' => 50
 'D' => 40
)

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用asort()功能

它对数组维护索引关联进行排序。

$arr = array('I' => 60, 'S' => 60, 'C' => 50, 'D' => 40);
asort($arr);

但是你不应该期望某个排序顺序是相等的值,因为如果任何sort函数将两个成员计算为相等,那么顺序是未定义的(排序不稳定)。

您可以通过为键和值创建2个辅助数组来实现按值和键排序,然后使用array_multisort函数:

$arr = array(
    'I' => 60,
    'S' => 60,
    'C' => 50,
    'D' => 40
);

$tag = array();
$num = array();

foreach($arr as $key => $value){
    $tag[] = $key;
    $num[] = $value;
}

array_multisort($num, SORT_DESC, $tag, SORT_ASC, $arr);

var_dump($arr);

/* result of var_dump($arr):
array (size=4)
  'I' => int 60
  'S' => int 60
  'C' => int 50
  'D' => int 40
*/

答案 1 :(得分:0)

$array = array(    
    'C'=>60, 
    'S'=>10,
    'I'=>20,
    'D'=>60
);

arsort($array); //sorts in descending order

$unique = array_unique($array,SORT_REGULAR); //get unique values - returns 60,20,10

$finalarray = array();
$order = array('D','I','S','C'); //defining the sort order priority
foreach($unique as $val){

    $key =  array_keys($array, $val); //get all keys that have the similar value (for duplicates)
        foreach($order as $val2){
            if(in_array($val2,$key)){ //check key according to order of priority keys
                $finalarray[$val2] = $array[$val2];
            }

        }

}

var_dump($finalarray);

Fiddle here.