krsort

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

krsortTrie un tableau en fonction des clés en ordre décroissant

Description

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

Trie array sur place suivant les clés en ordre décroissant.

Note:

Si deux membres se comparent comme égaux, ils maintiennent leur ordre original. Antérieur à PHP 8.0.0, leur ordre relatif dans le tableau trié n'est pas défini.

Note:

Réinitialise le pointeur interne du tableau au premier élément.

Liste de paramètres

array

Le tableau d'entrée.

flags

Le deuxième paramètre optionnel flags peut être utilisé pour modifier le comportement de tri en utilisant ces valeurs :

Type de drapeaux de tri :

Valeurs de retour

Retourne toujours true.

Historique

Version Description
8.2.0 Le type de retour est maintenant true, auparavant il était bool.

Exemples

Exemple #1 Exemple avec krsort()

<?php
$fruits
= array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach (
$fruits as $key => $val) {
echo
"$key = $val\n";
}
?>

L'exemple ci-dessus va afficher :

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

Voir aussi

  • sort() - Trie un tableau en ordre croissant
  • ksort() - Trie un tableau en fonction des clés en ordre croissant
  • Les fonctions de tri des tableaux
add a note add a note

User Contributed Notes 2 notes

up
-28
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);
}
up
-31
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;
}
?>
To Top