Another way to do a case case-insensitive sort by key would simply be:
<?php
uksort($array, 'strcasecmp');
?>
Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.
配列のソート
PHP には配列をソートする関数が複数用意されています。 このページでは、それらの違いについて説明します。
主な相違点は次のとおりです。
- 配列のキーでソートするものと、値でソートするものがあります。 $array['キー'] = '値';
- キーと値の相関関係をソート後にも保持するものと保持しないものがあります。 保持しないものは、ソート後にキーを (0,1,2 ... と) 振りなおします。
- ソート順による違いがあります。アルファベット順、 昇順、降順、数値順、自然順、ランダム、ユーザ定義の順などです。
- 注意: ソート関数は、すべて配列自身を直接変更します。 ソートした配列を新しく作って返すわけではありません。
- これらのソート関数でふたつのメンバーが等しいと判断されたときの並び順は未定義です (ソート結果は場合によって変わる可能性があります)。
| 関数名 | ソートの基準 | キーと値の相関関係 | ソート順 | 関連する関数 |
|---|---|---|---|---|
| array_multisort() | 値 | 連想配列の場合は維持し、数値添字配列の場合は維持しない | 最初の配列、あるいはソートオプション | array_walk() |
| asort() | 値 | 維持する | 昇順 | arsort() |
| arsort() | 値 | 維持する | 降順 | asort() |
| krsort() | キー | 維持する | 降順 | ksort() |
| ksort() | キー | 維持する | 昇順 | asort() |
| natcasesort() | 値 | 維持する | 大文字小文字を区別しない自然順 | natsort() |
| natsort() | 値 | 維持する | 自然順 | natcasesort() |
| rsort() | 値 | 維持しない | 降順 | sort() |
| shuffle() | 値 | 維持しない | ランダム | array_rand() |
| sort() | 値 | 維持しない | 昇順 | rsort() |
| uasort() | 値 | 維持する | ユーザ定義 | uksort() |
| uksort() | キー | 維持する | ユーザ定義 | uasort() |
| usort() | 値 | 維持しない | ユーザ定義 | uasort() |
oculiz at gmail dot com
12-Mar-2011 06:57
K.i.n.g.d.r.e.a.d
06-Apr-2010 03:29
If you search a feature which sorts an array incasesensitive by key, try this:
<?php
function isort($a,$b) {
return strtolower($a)>strtolower($b);
}
uksort($array, "isort");
?>
Dirk
29-Mar-2010 10:32
If you need to perform any of these sort functions on an array containing two or more equivalent values, you can get the equivalents to fall next to each other within the overall ordering (similar to how MySQL's ORDER BY works...) instead of breaking the sort() function, by using ksort() as a second parameter to arbitrarily distinguish any equivalent values by their unique keys:
<?php
sort($array, ksort($array));
?>
Seems like this effect should be built in. At least the workaround is so short...
