PHP 8.3.4 Released!

krsort

(PHP 4, PHP 5, PHP 7, PHP 8)

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

说明

krsort(array &$array, int $flags = SORT_REGULAR): true

array 本身按照键(key)降序排序。

注意:

如果两个成员完全相同,那么它们将保持原来的顺序。 在 PHP 8.0.0 之前,它们在排序数组中的相对顺序是未定义的。

注意:

重置数组中的内部指针,指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为:

排序类型标记:

返回值

总是返回 true

更新日志

版本 说明
8.2.0 现在返回类型为 true;之前是 bool

示例

示例 #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

参见

add a note

User Contributed Notes 2 notes

up
-33
Anonymous
18 years ago
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;
}
?>
up
-34
peter at pmkmedia dot com
20 years ago
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);
}
To Top