- ksort
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- User Contributed Notes 16 notes
- Sorting Arrays
- User Contributed Notes 2 notes
- Сортировка массивов
- Сортировка массива по ключу
- Результат:
- Сортировка массива по значению
- Результат:
- Результат:
- Естественная сортировка
- Результат:
- Результат:
- Сортировка многомерных массивов
- Результат:
- Сортировка многомерного массива по значению одного ключа
- Результат:
- Перемешать массив
- Результат:
ksort
Note:
If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
Note:
Resets array’s internal pointer to the first element.
Parameters
The optional second parameter flags may be used to modify the sorting behavior using these values:
- SORT_REGULAR — compare items normally; the details are described in the comparison operators section
- SORT_NUMERIC — compare items numerically
- SORT_STRING — compare items as strings
- SORT_LOCALE_STRING — compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale()
- SORT_NATURAL — compare items as strings using «natural ordering» like natsort()
- SORT_FLAG_CASE — can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively
Return Values
Always returns true .
Changelog
Version | Description |
---|---|
8.2.0 | The return type is true now; previously, it was bool . |
Examples
Example #1 ksort() example
$fruits = array( «d» => «lemon» , «a» => «orange» , «b» => «banana» , «c» => «apple» );
ksort ( $fruits );
foreach ( $fruits as $key => $val ) echo » $key = $val \n» ;
>
?>?php
The above example will output:
a = orange b = banana c = apple d = lemon
Example #2 ksort() with int keys
$a = [ 0 => ‘First’ , 2 => ‘Last’ , 1 => ‘Middle’ ];
var_dump ( $a );
ksort ( $a );
var_dump ( $a );
?>?php
The above example will output:
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" >
See Also
- sort() — Sort an array in ascending order
- krsort() — Sort an array by key in descending order
- The comparison of array sorting functions
User Contributed Notes 16 notes
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:
$people = array(
array( «name» => «Bob» , «age» => 8 , «colour» => «red» ),
array( «name» => «Greg» , «age» => 12 , «colour» => «blue» ),
array( «name» => «Andy» , «age» => 5 , «colour» => «purple» ));
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:
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.
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’,
];
Array
(
[-5] => minus five
[0] => zero
[1] => one
[2] => two
[100] => hundred
)
——————————————
DESCRIPTION: Keys are string numbers + default flag (SORT_REGULAR)
Array
(
[-5] => minus five
[0] => zero
[1] => one
[2] => two
[100] => hundred
)
——————————————
DESCRIPTION: Keys are string numbers + SORT_STRING flag
Array
(
[-5] => minus five
[0] => zero
[1] => one
[100] => hundred
[2] => two
)
DESCRIPTION: Keys are string numbers + SORT_NUMERIC flag
Array
(
[-5] => minus five
[0] => zero
[1] => one
[2] => two
[100] => hundred
)
here 2 functions to ksort/uksort an array and all its member arrays
I wrote this function to sort the keys of an array using an array of keynames, in order.
/**
* 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’ );
?>
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:
If you want to use the more natural syntax:
Then use this modified version:
foreach ($keys as $k) $new_array[$k] = $array[$k];
>
$array = $new_array;
return true;
>
Sorting Arrays
PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out.
- Some sort based on the array keys, whereas others by the values: $array[‘key’] = ‘value’;
- Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 . )
- The order of the sort: alphabetical, ascending (low to high), descending (high to low), natural, random, or user defined
- Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array
- If any of these sort functions evaluates two members as equal then they retain their original order. Prior to PHP 8.0.0, their order were undefined (the sorting was not stable).
Function name | Sorts by | Maintains key association | Order of sort | Related functions |
---|---|---|---|---|
array_multisort() | value | string keys yes, int keys no | first array or sort options | array_walk() |
asort() | value | yes | ascending | arsort() |
arsort() | value | yes | descending | asort() |
krsort() | key | yes | descending | ksort() |
ksort() | key | yes | ascending | krsort() |
natcasesort() | value | yes | natural, case insensitive | natsort() |
natsort() | value | yes | natural | natcasesort() |
rsort() | value | no | descending | sort() |
shuffle() | value | no | random | array_rand() |
sort() | value | no | ascending | rsort() |
uasort() | value | yes | user defined | uksort() |
uksort() | key | yes | user defined | uasort() |
usort() | value | no | user defined | uasort() |
User Contributed Notes 2 notes
While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.
function usortTest ( $a , $b ) var_dump ( $a );
var_dump ( $b );
return — 1 ;
>
$test = array( ‘val1’ );
usort ( $test , «usortTest» );
$test2 = array( ‘val2’ , ‘val3’ );
usort ( $test2 , «usortTest» );
The first array doesn’t get sent to the function.
Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.
Another way to do a case case-insensitive sort by key would simply be:
uksort ( $array , ‘strcasecmp’ );
?>
Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.
Сортировка массивов
В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в PHP существует множество функций, их подробное описание можно посмотреть на php.net, рассмотрим некоторые примеры.
Сортировка массива по ключу
ksort() и krsort() – сортирует массив по ключу.
$array = array( 3 => 'яблоко', 1 => 'апельсин', 5 => 'виноград' ); // По возрастанию: ksort($array); print_r($array); // По убыванию: krsort($array); print_r($array);
Результат:
Array ( [1] => апельсин [3] => яблоко [5] => виноград ) Array ( [5] => виноград [3] => яблоко [1] => апельсин )
Сортировка массива по значению
Функции sort() и rsort() сортирует массив по значению, при этом не сохраняя ключи.
$array = array( 3 => 'яблоко', 1 => 'апельсин', 5 => 'виноград' ); // По возрастанию: sort($array); print_r($array); // По убыванию: rsort($array); print_r($array);
Результат:
Array ( [0] => апельсин [1] => виноград [2] => яблоко ) Array ( [0] => яблоко [1] => виноград [2] => апельсин )
Чтобы сохранить ключи применяется функции asort() и arsort() .
$array = array( 3 => 'яблоко', 1 => 'апельсин', 5 => 'виноград' ); // По возрастанию: asort($array); print_r($array); // По убыванию: arsort($array); print_r($array);
Результат:
Array ( [1] => апельсин [5] => виноград [3] => яблоко ) Array ( [3] => яблоко [5] => виноград [1] => апельсин )
Естественная сортировка
Выше приведенные функции по умолчанию используют алгоритм Quicksort (быстрая сортировка). Чтобы изменить алгоритм нужно вторым аргументом указать флаг:
SORT_REGULAR | Обычное сравнение элементов (без изменения типов) |
SORT_NUMERIC | Числовое сравнение элементов |
SORT_STRING | Строковое сравнение элементов |
SORT_LOCALE_STRING | Сравнивает элементы как строки с учетом текущей локали. |
SORT_NATURAL | Также как natsort() |
SORT_FLAG_CASE | Может быть объединен с SORT_STRING или SORT_NATURAL для сортировки строк без учета регистра. |
Привычную для человека сортировку делают функции natsort() , natcasesort() или флаг SORT_NATURAL .
natcasesort() сортирует массив без учета регистра символов.
Разницу можно увидеть в примере:
$array = array(-1, 0, 10, 'текст', 'a', 'b'); // Quicksort: sort($array); print_r($array); // Natural order: natsort($array); print_r($array);
Результат:
Array ( [0] => -1 [1] => a [2] => b [3] => 0 [4] => текст [5] => 10 ) Array ( [0] => -1 [1] => 0 [2] => 10 [4] => a [5] => b [3] => текст )
У natsort() нет возможности изменить направление сортировки, поэтому можно применить функцию array_reverse() .
natsort($array); $array = array_reverse($array); print_r($array);
Результат:
Array ( [0] => текст [1] => b [2] => a [3] => 10 [4] => 0 [5] => -1 )
Сортировка многомерных массивов
array_multisort() сортирует многомерные массивы по значению, также может отсортировать сразу несколько массивов.
$array = array( array(20, 222, 2, 22), array(10, 111, 1, 11), ); array_multisort($array); print_r($array);
Результат:
Array ( [0] => Array( [0] => 10 [1] => 111 [2] => 1 [3] => 11 ) [1] => Array( [0] => 20 [1] => 222 [2] => 2 [3] => 22 ) )
Чтобы изменить направление сортировки вторым аргументом функции указывается SORT_ASC или SORT_DESC .
array_multisort($array, SORT_DESC); print_r($array);
Сортировка многомерного массива по значению одного ключа
Есть несколько вариантов, первый – uasort() , сортирует массив, используя пользовательскую функцию для сравнения элементов и сохранением ключей.
В примере сортировка идет по ключу « count ».
$array = array( array( 'sku' => '645908-463', 'count' => '1' ), array( 'sku' => '64590644', 'count' => '20' ), array( 'sku' => '7543', 'count' => '2' ) ); // По возрастанию: function cmp_function($a, $b) < return ($a['count'] >$b['count']); > uasort($array, 'cmp_function'); print_r($array); // По убыванию: function cmp_function_desc($a, $b) < return ($a['count'] < $b['count']); >uasort($array, 'cmp_function_desc'); print_r($array);
Результат:
Array ( [0] => Array( [sku] => 645908-463 [count] => 1 ) [2] => Array( [sku] => 7543 [count] => 2 ) [1] => Array( [sku] => 64590644 [count] => 20 ) ) Array ( [1] => Array( [sku] => 64590644 [count] => 20 ) [2] => Array( [sku] => 7543 [count] => 2 ) [0] => Array( [sku] => 645908-463 [count] => 1 ) )
Второй вариант на основе функции array_multisort() :
function array_multisort_value() < $args = func_get_args(); $data = array_shift($args); foreach ($args as $n =>$field) < if (is_string($field)) < $tmp = array(); foreach ($data as $key =>$row) < $tmp[$key] = $row[$field]; >$args[$n] = $tmp; > > $args[] = &$data; call_user_func_array('array_multisort', $args); return array_pop($args); > $array = array( array( 'sku' => '645908-463', 'count' => '1' ), array( 'sku' => '64590644', 'count' => '20' ), array( 'sku' => '7543', 'count' => '2' ) ); $array = array_multisort_value($array, 'count', SORT_DESC); print_r($array);
Перемешать массив
Функция shuffle() перемешивает массив в случайном порядке, не сохроняя ключи.
$array = array( 1 => 'яблоко', 2 => 'апельсин', 3 => 'виноград' ); shuffle($array); print_r($array); shuffle($array); print_r($array);
Результат:
Array ( [0] => виноград [1] => яблоко [2] => апельсин ) Array ( [0] => виноград [1] => апельсин [2] => яблоко )