krsort

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

krsort配列をキーで降順にソートする

説明

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

配列をキーにより降順にソートします。キーとデータとの関係は維持されます。 この関数は主に連想配列の場合に有用です。

パラメータ

array

入力の配列。

flags

オプションの第二引数 flags によりソートの動作を修正可能です。 使える値は下記の通りです:

ソートタイプのフラグ:

  • SORT_REGULAR - 通常通りに項目を比較します。 詳細は 比較演算子 で説明されています。
  • SORT_NUMERIC - 数値として項目を比較します。
  • SORT_STRING - 文字列として項目を比較します。
  • SORT_LOCALE_STRING - 現在のロケールに基づいて、文字列として項目を比較します。 比較に使うロケールは、setlocale() 関数で変更できます。
  • SORT_NATURAL - 要素の比較を文字列として行い、 natsort() と同様の「自然順」で比較します。
  • SORT_FLAG_CASE - SORT_STRINGSORT_NATURAL と (ビットORで) 組み合わせて使い、 文字列のソートで大文字小文字を区別しないようにします。

返り値

成功した場合に true を、失敗した場合に false を返します。

例1 krsort() の例

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

上の例の出力は以下となります。

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

参考

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