PHP: krsort - Manual

downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

ksort key

Last updated: Sat, 27 Jan 2007

view this page in

# krsort

(PHP 3 >= 3.0.13, PHP 4, PHP 5)

krsort -- Отсортировать массив по ключам в обратном порядке

## Описание

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

Сортирует массив по ключам в обратном порядке, сохраняя отношения между ключами и значениями. Функция полезна, в основном, для работы с ассоциативными массивами.

Возвращает `TRUE` в случае успешного завершения или `FALSE` в случае возникновения ошибки.

Пример 1. Пример использования krsort()

`<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo "$key = $val
";
}
?>`

Результат выполнения данного примера:

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

Вы можете изменить поведение сортировки, используя дополнительный параметр `sort_flags`, подробнее см. sort().

См. также asort(), arsort(), ksort(), sort(), natsort() и rsort().

add a note User Contributed Notes
krsort
07-Aug-2005 06: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 01: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 12: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...`
add a note
ksort key

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST