ksort
(PHP 4, PHP 5, PHP 7, PHP 8)
ksort — 配列をキーで昇順にソートする
説明
array
をキーで昇順にソートします。
注意:
比較結果が等しくなる二つの要素があった場合、それらの並び順は保持されます。PHP 8.0.0 より前のバージョンでは、ソートした配列におけるそれらの並び順は不定でした。
注意:
この関数をコールすると、配列の内部ポインタは最初の要素にリセットされます。
パラメータ
array
-
入力の配列。
flags
-
オプションの第二引数
flags
によりソートの動作を修正可能です。 使える値は下記の通りです:ソートタイプのフラグ:
-
SORT_REGULAR
- 通常通りに項目を比較します。 詳細は 比較演算子 で説明されています。 -
SORT_NUMERIC
- 数値として項目を比較します。 -
SORT_STRING
- 文字列として項目を比較します。 -
SORT_LOCALE_STRING
- 現在のロケールに基づいて、文字列として項目を比較します。 比較に使うロケールは、setlocale() 関数で変更できます。 -
SORT_NATURAL
- 要素の比較を文字列として行い、 natsort() と同様の「自然順」で比較します。 -
SORT_FLAG_CASE
-SORT_STRING
やSORT_NATURAL
と (ビットORで) 組み合わせて使い、 文字列のソートで大文字小文字を区別しないようにします。
-
戻り値
常に true
を返します。
変更履歴
バージョン | 説明 |
---|---|
8.2.0 |
戻り値の型が、true になりました。これより前のバージョンでは、bool でした。
|
8.2.0 |
SORT_REGULAR を使って数値文字列の比較を行う際に、
PHP 8 で標準になっているルールを使うようになりました。
|
例
例1 ksort() の例
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
上の例の出力は以下となります。
a = orange b = banana c = apple d = lemon
例2 数値がキーの場合の ksort() の振る舞い
<?php
$a = [0 => 'First', 2 => 'Last', 1 => 'Middle'];
var_dump($a);
ksort($a);
var_dump($a);
?>
上の例の出力は以下となります。
array(3) { [0]=> string(5) "First" [2]=> string(4) "Last" [1]=> string(6) "Middle" } array(3) { [0]=> string(5) "First" [1]=> string(6) "Middle" [2]=> string(4) "Last" }
参考
- sort() - 配列を昇順にソートする
- krsort() - 配列をキーで降順にソートする
- 配列ソート関数の比較
+add a note
User Contributed Notes 16 notes
DavidG ¶
14 years ago
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
var_dump($people);
$sortArray = array();
foreach($people as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_DESC,$people);
var_dump($people);
?>
Output from first var_dump:
[0]=>
array(3) {
["name"]=>
string(3) "Bob"
["age"]=>
int(8)
["colour"]=>
string(3) "red"
}
[1]=>
array(3) {
["name"]=>
string(4) "Greg"
["age"]=>
int(12)
["colour"]=>
string(4) "blue"
}
[2]=>
array(3) {
["name"]=>
string(4) "Andy"
["age"]=>
int(5)
["colour"]=>
string(6) "purple"
}
}
Output from 2nd var_dump:
array(3) {
[0]=>
array(3) {
["name"]=>
string(4) "Greg"
["age"]=>
int(12)
["colour"]=>
string(4) "blue"
}
[1]=>
array(3) {
["name"]=>
string(3) "Bob"
["age"]=>
int(8)
["colour"]=>
string(3) "red"
}
[2]=>
array(3) {
["name"]=>
string(4) "Andy"
["age"]=>
int(5)
["colour"]=>
string(6) "purple"
}
There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
orlov0562 at gmail dot com ¶
7 years ago
The first thing that I didn't find in description it's that this function return results from MIN value to MAX value, ex: [-5=>'', 0=>'', 5=>'' ]
Also you should know that by default, it has correct sorting for keys that represented as string but has a number as value, ex: ['-5'=>'', '0'=>'', '5'=>'' ]
Few examples with results:
-----------------------------------------
DESCRIPTION: Keys are numbers + default flag (SORT_REGULAR)
$arr = [
-5 => 'minus five',
0 => 'zero',
1 => 'one',
2 => 'two',
100 => 'hundred',
];
ksort($arr);
print_r($arr);
RESULT:
Array
(
[-5] => minus five
[0] => zero
[1] => one
[2] => two
[100] => hundred
)
-----------------------------------------
DESCRIPTION: Keys are string numbers + default flag (SORT_REGULAR)
$arr = [
'-5' => 'minus five',
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'100' => 'hundred',
];
ksort($arr);
print_r($arr);
RESULT:
Array
(
[-5] => minus five
[0] => zero
[1] => one
[2] => two
[100] => hundred
)
-----------------------------------------
DESCRIPTION: Keys are string numbers + SORT_STRING flag
$arr = [
'-5' => 'minus five',
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'100' => 'hundred',
];
ksort($arr, SORT_STRING);
print_r($arr);
RESULT:
Array
(
[-5] => minus five
[0] => zero
[1] => one
[100] => hundred
[2] => two
)
-----------------------------------------
DESCRIPTION: Keys are string numbers + SORT_NUMERIC flag
$arr = [
'-5' => 'minus five',
'0' => 'zero',
'1' => 'one',
'2' => 'two',
'100' => 'hundred',
];
ksort($arr, SORT_NUMERIC);
print_r($arr);
RESULT:
Array
(
[-5] => minus five
[0] => zero
[1] => one
[2] => two
[100] => hundred
)
thegrandoverseer ¶
12 years ago
I wrote this function to sort the keys of an array using an array of keynames, in order.
<?php
/**
* function array_reorder_keys
* reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
* @param array &$array - the array to reorder
* @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
*/
function array_reorder_keys(&$array, $keynames){
if(empty($array) || !is_array($array) || empty($keynames)) return;
if(!is_array($keynames)) $keynames = explode(',',$keynames);
if(!empty($keynames)) $keynames = array_reverse($keynames);
foreach($keynames as $n){
if(array_key_exists($n, $array)){
$newarray = array($n=>$array[$n]); //copy the node before unsetting
unset($array[$n]); //remove the node
$array = $newarray + array_filter($array); //combine copy with filtered array
}
}
}
$seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
array_reorder_keys($seed_array, 'baz,foo,bar'); //returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' );
?>
Anonymous ¶
22 years ago
here 2 functions to ksort/uksort an array and all its member arrays
function tksort(&$array)
{
ksort($array);
foreach(array_keys($array) as $k)
{
if(gettype($array[$k])=="array")
{
tksort($array[$k]);
}
}
}
function utksort(&$array, $function)
{
uksort($array, $function);
foreach(array_keys($array) as $k)
{
if(gettype($array[$k])=="array")
{
utksort($array[$k], $function);
}
}
}
ssb45 at cornell dot edu ¶
19 years ago
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is. While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched. Thus, you must use this syntax:
$array = natksort($array);
If you want to use the more natural syntax:
$status = natksort($array);
Then use this modified version:
function natksort(&$array) {
$keys = array_keys($array);
natcasesort($keys);
foreach ($keys as $k) {
$new_array[$k] = $array[$k];
}
$array = $new_array;
return true;
}
bimal at sanjaal dot com ¶
10 years ago
An example of reverse sorting a domain name by its name.
<?php
$domains = array(
'sub.domain.com',
'sub2.domain.com',
);
foreach($domains as $d => $domain)
{
$chunks = explode('.', $domain);
krsort($chunks);
echo "\r\n<br>", implode('/', $chunks);
}
/**
* Outputs as:
*
* com/domain/sub
* com/domain/sub2
*/
?>
sbarnum at mac dot com ¶
23 years ago
ksort on an array with negative integers as keys yields some odd results. Not sure if this is a bad idea (negative key values) or what.
delvach at mail dot com ¶
23 years ago
A real quick way to do a case-insensitive sort of an array keyed by strings:
uksort($myArray, "strnatcasecmp");
serpro at gmail dot com ¶
15 years ago
Here is a function to sort an array by the key of his sub-array.
<?php
function sksort(&$array, $subkey="id", $sort_ascending=false) {
if (count($array))
$temp_array[key($array)] = array_shift($array);
foreach($array as $key => $val){
$offset = 0;
$found = false;
foreach($temp_array as $tmp_key => $tmp_val)
{
if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
{
$temp_array = array_merge( (array)array_slice($temp_array,0,$offset),
array($key => $val),
array_slice($temp_array,$offset)
);
$found = true;
}
$offset++;
}
if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
}
if ($sort_ascending) $array = array_reverse($temp_array);
else $array = $temp_array;
}
?>
Example
<?php
$info = array("peter" => array("age" => 21,
"gender" => "male"
),
"john" => array("age" => 19,
"gender" => "male"
),
"mary" => array("age" => 20,
"gender" => "female"
)
);
sksort($info, "age");
var_dump($info);
sksort($info, "age", true);
var_dump($ifno);
?>
This will be the output of the example:
/*DESCENDING SORT*/
array(3) {
["peter"]=>
array(2) {
["age"]=>
int(21)
["gender"]=>
string(4) "male"
}
["mary"]=>
array(2) {
["age"]=>
int(20)
["gender"]=>
string(6) "female"
}
["john"]=>
array(2) {
["age"]=>
int(19)
["gender"]=>
string(4) "male"
}
}
/*ASCENDING SORT*/
array(3) {
["john"]=>
array(2) {
["age"]=>
int(19)
["gender"]=>
string(4) "male"
}
["mary"]=>
array(2) {
["age"]=>
int(20)
["gender"]=>
string(6) "female"
}
["peter"]=>
array(2) {
["age"]=>
int(21)
["gender"]=>
string(4) "male"
}
}
Anonymous ¶
11 years ago
Note that this function will output the given $fields in the order they were added to the data array and not automatically in numerical key order.
To output in ascending key order, you'll need to ksort the array first (or use appropriate natural order sorting, depending on your keys).
For example:
<?php
$data[2] = 'C';
$data[0] = 'A';
$data[1] = 'B';
fputcsv($fh, $data); // outputs: "C,A,B"
ksort($data);
fputcsv($fh, $data); // outputs: "A,B,C"
?>
Anonymous ¶
10 years ago
@thegrandoverseer
you could also use the build-in php array functions to get exactly what you want to have:
<?php
$seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
$keys_array = array('baz', 'foo', 'bar');
$return_array = array_intersect_key($seed_array, array_flip($keys_array)) + array_diff_key($seed_array, array_flip($keys_array));
?>
justin at booleangate dot org ¶
19 years ago
Here's a handy function for natural order sorting on keys.
function natksort($array) {
// Like ksort but uses natural sort instead
$keys = array_keys($array);
natsort($keys);
foreach ($keys as $k)
$new_array[$k] = $array[$k];
return $new_array;
}
jakub dot lopuszanski at nasza-klasa dot pl ¶
13 years ago
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
"a"=>"A",
0=>"A",
"b"=>"A",
1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>
produces (on PHP 5.3.6-4 with Suhosin-Patch) :
array(4) {
["a"]=>
string(1) "A"
[0]=>
string(1) "A"
["b"]=>
string(1) "A"
[1]=>
string(1) "A"
}
array(4) {
["b"]=>
string(1) "A"
[0]=>
string(1) "A"
["a"]=>
string(1) "A"
[1]=>
string(1) "A"
}
note that the second array should be sorted by keys, but is even more messed up than the first one!