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;
}
?>
krsort
(PHP 4, PHP 5)
krsort — Ordena um array pelas chaves em ordem descrescente
Descrição
bool krsort
( array &$array
[, int $sort_flags
] )
Ordena um array pelas chaves em ordem descrescente, mantendo a correlação entre entre as chaves e os valores. Essa função é bastante útil em arrays associativos.
Parâmetros
- array
-
O array de entrada.
- sort_flags
-
Você pode modificar o comportamento da ordenação usando o parâmetro opcional sort_flags, para detalhes veja sort().
Valor Retornado
Retorna TRUE em caso de sucesso ou FALSE em falhas.
Exemplos
Exemplo #1 Exemplo de krsort()
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
O exemplo acima irá imprimir:
d = limao c = melancia b = banana a = laranja
Veja Também
- asort() - Ordena um array mantendo a associação entre índices e valores
- arsort() - Ordena um array em ordem descrescente mantendo a associação entre índices e valores
- ksort() - Ordena um array pelas chaves
- sort() - Ordena um array
- natsort() - Ordena um array utilizando o algoritmo da "ordem natural"
- rsort() - Ordena um array em ordem descrescente
07-Aug-2005 12:37
peter at pmkmedia dot com
07-Nov-2003 06: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 05: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...
