数组 函数
在线手册:中文 英文
PHP手册

krsort

(PHP 4, PHP 5)

krsort对数组按照键名逆向排序

说明

bool krsort ( array &$array [, int $sort_flags ] )

对数组按照键名逆向排序,保留键名到数据的关联。主要用于结合数组。

成功时返回 TRUE, 或者在失败时返回 FALSE.

Example #1 krsort() 例子

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

以上例程会输出:

d = lemon
c = apple
b = banana
a = orange

可以用可选参数 sort_flags 改变排序的行为,详情见 sort()

参见 asort()arsort()ksort()sort()natsort()rsort()

参数

array

The input array.

sort_flags

You may modify the behavior of the sort using the optional parameter sort_flags, for details see sort().

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE.

范例

Example #2 krsort() example

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

以上例程会输出:

d = lemon
c = apple
b = banana
a = orange

参见


数组 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 对数组按照键名逆向排序

用户评论:

(08-Aug-2005 02:37)

To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
   
$keys = array_keys($array);
   
natsort($keys);

    foreach (
$keys as $k)
    {
       
$new_array[$k] = $array[$k];
    }
  
   
$new_array = array_reverse($new_array, true);

    return
$new_array;
}
?>

peter at pmkmedia dot com (07-Nov-2003 09:51)

Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}

lolo at phpheaven dot net (28-Nov-2000 08:33)

If you want to emulate the krsort function for an older version of php, you can use this piece of code:

function KeyComp($a, $b)
{  
  return -(strcmp($a,$b));
}

function krsort($MyArray)
{
  uksort($MyArray, "KeyComp");
}

Maybe obvious and useless, but who knows...