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);
}
krsort
(PHP 4, PHP 5)
krsort — Ordena un array por clave en orden inverso
Descripción
bool krsort
( array
&$array
[, int $sort_flags = SORT_REGULAR
] )Ordena un array por clave en orden inverso, manteniendo la correlación entre la clave y los datos. Esto es útil principalmente para arrays asociativos.
Parámetros
-
array -
El array de entrada.
-
sort_flags -
Se puede modificar el comportamiento del ordenado usando el parámetro opcional
sort_flags, par más información vea sort().
Valores devueltos
Devuelve TRUE en caso de éxito o FALSE en caso de error.
Ejemplos
Ejemplo #1 Ejemplo de krsort()
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
El resultado del ejemplo serÃa:
d = lemon c = apple b = banana a = orange
Ver también
- arsort() - Ordena un array en orden inverso y mantiene la asociación de índices
- ksort() - Ordena un array por clave
- comparación de funciones de orden de arrays
peter at pmkmedia dot com ¶
9 years ago
Anonymous ¶
7 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;
}
?>
lolo at phpheaven dot net ¶
12 years ago
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...
