PHP 5.4.31 Released

krsort

(PHP 4, PHP 5)

krsortOrdina rispetto alle chiavi di un array in ordine inverso

Descrizione

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

Ordina un array rispetto alle sue chiavi, in ordine inverso, mantenendo le associazioni. Questa funzione è utile con gli array associativi.

Restituisce TRUE in caso di successo, FALSE in caso di fallimento.

Example #1 Esempio di krsort()

<?php
$frutti 
= array("d"=>"limone""a"=>"arancio""b"=>"banana""c"=>"mela");
krsort($frutti);
reset($frutti);
while (list(
$chiave$valore) = each($frutti)) {
    echo 
"$chiave = $valore\n";
}
?>

Questo esempio mostrerà:

d = limone
c = mela
b = banana
a = arancio

Si può modificare il comportamento dell'ordinamento usando il parametro opzionale sort_flags, per ulteriori dettagli vedere sort().

Vedere anche asort(), arsort(), ksort(), sort(), natsort() e rsort().

add a note add a note

User Contributed Notes 3 notes

up
1
peter at pmkmedia dot com
10 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);
}
up
0
marcus at synchromedia dot co dot uk
5 days ago
Note that you can sort subarrays within a larger structure without sorting the whole thing:

<?php
$fruits
= array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple", 'e' => array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"));
krsort($fruits['e']);
var_dump($fruits);
?>

array(5) {
  ["d"]=>
  string(5) "lemon"
  ["a"]=>
  string(6) "orange"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(5) "apple"
  ["e"]=>
  array(4) {
    ["d"]=>
    string(5) "lemon"
    ["c"]=>
    string(5) "apple"
    ["b"]=>
    string(6) "banana"
    ["a"]=>
    string(6) "orange"
  }
}

You can see that it only sorts the items within the 'e' element.
up
-2
Anonymous
8 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;
}
?>
To Top