Php array ksort key

PHP ksort: How to sort array by key in PHP

Key-value associations become essential when you are dealing with associative arrays. The ksort() function is useful mainly for associative arrays.

One of PHP’s most robust data types is an array. It can hold numbers and contain characters; it can be sliced, sorted, and chunked. The specific sorting functions are only for sorting by the keys or values when sorting the array.

PHP ksort

PHP ksort() is a built-in function that sorts the associative array in ascending order, according to the key. It sorts an array by key, maintaining the key to data correlations.

We can use the ksort() function for sorting the associative array by key alphabetically in ascending order while maintaining a relationship between the key and data.

For example, you might have an array with info about the total number of airport terminals in various countries.

Assuming that all the names of different countries are the keys and the numbers of the airports are values, you might want to sort all the country names alphabetically.

It is straightforward to do with the ksort() and krsort() functions. Both these functions will maintain a key-value association of the array items after sorting.

A ksort() function sorts the keys from low to high, and the krsort() sorts the keys from high to low.

Syntax

Parameters

The array parameter is required, and it tells the array to sort.

The sorttype is optional and specifies how to compare the array of elements/items. Possible values:

  1. 0 = SORT_REGULAR – Default. Compare elements normally (don’t change types).
  2. 1 = SORT_NUMERIC – Compare elements numerically.
  3. 2 = SORT_STRING – Compare elements as strings.
  4. 3 = SORT_LOCALE_STRING – Compare elements as strings based on the current locale.
  5. 4 = SORT_NATURAL – Compare elements as strings using natural ordering.

How To Sort Array By Key in PHP

The ksort() and krsort make PHP sort associative arrays, but they don’t do it by the value of an associative array: what matters here is a key. In our example, names were the keys.

Hence, using these two functions will sort the cast name and age.

We can use ksort() for ascending order.

 15, 'Finn' => 16, 'Noah' => 15 ]; ksort($stcast); print_r($stcast);
➜ pro php app.php Array ( [Finn] => 16 [Millie] => 15 [Noah] => 15 ) ➜ pro

Sorting the associative array by a specific key

Do you have the array of arrays and want to sort by a specific key in the array? That’s where usort() comes in. First, let’s get our array set up:

 'Millie', 'age' => 15), array('name' => 'Finn', 'age' => 16), array('name' => 'Caleb', 'age' => 17), array('name' => 'Gaten', 'age' => 16), array('name' => 'Noah', 'age' => 15), );

The array above comprises arrays that hold the cast’s name and age. It’s mixed up on purpose so that we can sort it.

Читайте также:  Python add new column to dataframe

To use usort(), we either need to create a function or use an anonymous function that’s passed it at run time.

I’m opting to use the separate functions for the examples but will elaborate on how to make an awesome function that’s reusable for any field.

If we want to start, let’s create two functions, 1 to sort by name and one to sort by age.

See the following full program.

 'Millie', 'age' => 15), array('name' => 'Finn', 'age' => 16), array('name' => 'Caleb', 'age' => 17), array('name' => 'Gaten', 'age' => 16), array('name' => 'Noah', 'age' => 15), ); function sortByName($a, $b) < $a = $a['name']; $b = $b['name']; if ($a == $b) return 0; return ($a < $b) ? -1 : 1; >function sortByAge($a, $b) < $a = $a['age']; $b = $b['age']; if ($a == $b) return 0; return ($a < $b) ? -1 : 1; >echo 'Sort by Name'; usort($stcast, 'sortByName'); print_r($stcast); echo 'Sort by Age'; usort($stcast, 'sortByAge'); print_r($stcast);
➜ pro php app.php Sort by NameArray ( [0] => Array ( [name] => Caleb [age] => 17 ) [1] => Array ( [name] => Finn [age] => 16 ) [2] => Array ( [name] => Gaten [age] => 16 ) [3] => Array ( [name] => Millie [age] => 15 ) [4] => Array ( [name] => Noah [age] => 15 ) ) Sort by AgeArray ( [0] => Array ( [name] => Millie [age] => 15 ) [1] => Array ( [name] => Noah [age] => 15 ) [2] => Array ( [name] => Gaten [age] => 16 ) [3] => Array ( [name] => Finn [age] => 16 ) [4] => Array ( [name] => Caleb [age] => 17 ) ) ➜ pro

So this is how you sort the array by key or value in numerical, alphabetical, descending, and ascending order in PHP.

Some functions in PHP can only be applied to the associative arrays.

That’s it for this tutorial.

Источник

krsort

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 .
Читайте также:  Date Selector

Examples

Example #1 krsort() example

$fruits = array( «d» => «lemon» , «a» => «orange» , «b» => «banana» , «c» => «apple» );
krsort ( $fruits );
foreach ( $fruits as $key => $val ) echo » $key = $val \n» ;
>
?>

The above example will output:

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

See Also

  • sort() — Sort an array in ascending order
  • ksort() — Sort an array by key in ascending order
  • The comparison of array sorting functions

User Contributed Notes 2 notes

To create a natural reverse sorting by keys, use the following function:

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 );

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);
>

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    Сортировка массивов

    В продолжении темы работы с массивами поговорим о типичной задаче – их сортировке. Для ее выполнения в 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] => яблоко ) 

    Источник

Оцените статью