krsort

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

krsort Sortiert ein Array nach Schlüsseln in umgekehrter Reihenfolge

Beschreibung

krsort ( array &$array , int $sort_flags = SORT_REGULAR ) : bool

Sortiert ein Array nach Schlüsseln in umgekehrter Reihenfolge, wobei die Zuordnungen zwischen Schlüssel und Wert erhalten bleiben. Dies ist hauptsächlich bei assoziativen Arrays hilfreich.

Parameter-Liste

array

Das Eingabe-Array.

sort_flags

Sie können das Verhalten der Sortierung mittels dem optionalen Parameter sort_flags beeinflussen, für Details siehe sort().

Rückgabewerte

Gibt bei Erfolg true zurück. Im Fehlerfall wird false zurückgegeben.

Beispiele

Beispiel #1 krsort()-Beispiel

<?php
$fruits 
= array("d" => "Zitrone""a" => "Orange""b" => "Banane""c" => "Apfel");
krsort($fruits);
foreach (
$fruits as $key => $val) {
    echo 
"$key = $val\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

d = Zitrone
c = Apfel
b = Banane
a = Orange

Siehe auch

add a note add a note

User Contributed Notes 2 notes

up
-26
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
-29
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