Learn to php sort array by key or value: tips and examples

Введение в сортировку массивов в PHP

Довольно часто приходится сортировать данные в массивах. Возможно, вам нужно это делать в алфавитном или числовом порядке, в порядке возрастания или убывания. Для этого PHP предоставляет несколько полезных функций. В следующем разделе мы покажем вам, как использовать эти функции. Для начала возьмем небольшой массив в качестве примера:

<?php
$spisokTsvetov = array(
  "apple"  => "red",
  "grass"  => "green",
  "sky"    => "blue",
  "night"  => "black",
  "wall"   => "white"
);
?>

Теперь, если вы выведете массив, вы увидите элементы в том же порядке, в котором они были определены:

<?php
foreach ($spisokTsvetov as $key => $value) {
  echo '<p>' . $key . ' - ' . $value . '</p>';
}
?>

Результат будет следующим:

apple - red
grass - green
sky - blue
night - black
wall - white

Теперь перейдем к процессу сортировки этого массива.

rsort()- Sort Array in Descending Order

There is the following function which sorts the elements of a numerical array in descending numerical order.
Let’s see the example, here also use it in the same script we saw in the example with the fruits name. therefore, The change of function will produce a different result:

<?php
$fruits = ;
rsort($fruits);
print_r($fruits);
?>

1
2
3
4
5

<?php

$fruits=’Graps’,’Mango’,’Apple’;

rsort($fruits);

print_r($fruits);

?>

Output:

Array ( => Mango => Graps => Apple )

1 Array(=>Mango1=>Graps2=>Apple)

Let’s do another example with the numbers. I hope you will notice the script produces an opposite result than sort() did in the previous example:

<?php
$numbers = ;
rsort($numbers);
print_r($numbers);
?>

1
2
3
4
5

<?php

$numbers=21,16,71,14,7,25;

rsort($numbers);

print_r($numbers);

?>

Output:

Array ( => 71 => 25 => 21 => 16 => 14 => 7 )

1 Array(=>711=>252=>213=>164=>145=>7)

Сортировка ассоциативных массивов

Все замечательно, однако, с ассоциативными массивами мы уже не сможем применить данные функции, так как они разрывают связь значения с ключом массива. Поэтому нам нужно познакомиться еще с некоторыми функциями, которые позволят нам сортировать ассоциативные массивы.

Как мы знаем, у ассоциативных массивов имеются ключи и значения. Следовательно, и сортировку можно производить по ключам, либо по значениям.

Давайте начнем с сортировки по значениям.

Для того, чтобы отсортировать значения ассоциативного массива в алфавитном порядке, мы применим функцию asort().

Для этого сначала создадим ассоциативный массив, применим функцию, выведем результат на экран.

<?
$Mass='Катя';
$Mass='Борис';
$Mass='Аня';
$Mass='Рита';
asort($Mass);
print_r($Mass);
?>

Как Вы видите, значения ассоциативного массива отсортированы в алфавитном порядке, однако, их связь с ключами сохранена.

Таким же образом работает, и функция arsort(), за тем исключением, что она сортирует значения ассоциативного массива в обратном порядке.

<?
$Mass='Катя';
$Mass='Борис';
$Mass='Аня';
$Mass='Рита';
arsort($Mass);
print_r($Mass);
?>

Здесь опять же мы можем видеть, что значения элементов массива сохраняют свою связь с ключами, но отсортированы в обратном порядке.

Тот же самый ассоциативный массив мы можем отсортировать и по ключам.

Как Вы, наверное, уже догадались это можно сделать в алфавитном или обратном порядке.

Для того, чтобы сортировать массив по ключам в алфавитном порядке, нам понадобится функция ksort().

<?
$Mass='Катя';
$Mass='Борис';
$Mass='Аня';
$Mass='Рита';
ksort($Mass);
print_r($Mass);
?>

Массив отсортирован по ключам в алфавитном порядке.

Для того, чтобы отсортировать массив по его ключам в обратном порядке, применяется функция krsort().

<?
$Mass='Катя';
$Mass='Борис';
$Mass='Аня';
$Mass='Рита';
krsort($Mass);
print_r($Mass);
?>

Думаю, что из скриншота все понятно.

sort()- Sort Array in Ascending Order

There is the following function sorts the elements of a numerical array in the ascending numerical order:

<?php
$numbers = ;
sort($numbers);
print_r($numbers);
?>

1
2
3
4
5

<?php

$numbers=21,16,71,14,7,25;

sort($numbers);

print_r($numbers);

?>

Output:

Array ( => 7 => 14 => 16 => 21 => 25 => 71 )

1 Array(=>71=>142=>163=>214=>255=>71)

Let’s see another example with a PHP array that holds the names of different Fruits names. furthermore, the code reveals how this function sorts the array in the alphabetical order:

<?php
$fruits = ;
sort($fruits);
print_r($fruits);
?>

1
2
3
4
5

<?php

$fruits=’Graps’,’Mango’,’Apple’;

sort($fruits);

print_r($fruits);

?>

Output:

Array ( => Apple => Graps => Mango )

1 Array(=>Apple1=>Graps2=>Mango)

Sorting on multiple fields

If you want to sort by lastname AND firstname, then you might think
that just applying two sorts in sequence would give you the desired
result:

Note that here we’ve specifed the current namespace
__NAMESPACE__ to make the code compatible with PHP namespaces. Otherwise any
function you pass has to exist in the global namespace.

You might think so, but since PHP version 4.1 the usort and
related functions will essentially shuffle the array before sorting (the
algorithm is ‘no longer stable’):

See our Quick Sort Algorithm
article for more detail.

This means that, after ordering by first name, the result of then
sorting
by last name will not necessarily retain the correct
order of first names.

So what’s the solution? We need a new function that can compare both
fields at the same time and then apply the sort:

Finally, the result we wanted:

index firstname lastname age
James Brown 31
Michael Davis 43
Mary Johnson 25
Amanda Miller 18
Patrick Miller 27
Sarah Miller 24
Patricia Williams 7

This function works because it first compares the last names, and
only if they are identical will it compare the first names to work out
the correct order.

You can extend this function to use more variables by inserting more
conditions every time $retval has a zero value.

Sorting based on a list of values

There are situations where it’s not possible to use a numeric or
alphabet-based sort routine. Suppose that you have the following
data to present on a website:

index name position
Mary Johnson Secretary
Amanda Miller Member
James Brown Member
Patricia Williams Member
Michael Davis President
Sarah Miller Vice-President
Patrick Miller Member

And that you want to sort these names by their position, based on the
following list:

Again, it’s not as difficult as you might think. All we need is the
following custom function:

If you don’t have a second field that you want to sort by, just
replace the highlighted line with return 0;

All we’re doing here is looking at the values in the
position field. If they’re identical then we sort by the
name field instead. Otherwise we do a comparison of where in
the sortorder list the relevant values appear and sort based on
that. The output is as follows:

index name position
Michael Davis President
Sarah Miller Vice-President
Mary Johnson Secretary
Amanda Miller Member
James Brown Member
Patricia Williams Member
Patrick Miller Member

As detailed above for simpler cases we can now enhance this function
to make it more generic and re-usable, but I’ll leave that as an
exercise for you. You would need pass the sortorder array to
the function along with details of which fields to sort by.

If you’re working on the web with this type of data, you might also
want to read the article Formatting Data as
HTML which presents instructions for converting PHP data to HTML
tables, lists and forms.

Using an ‘anonymous’ function

This is where it starts to get interesting. You can create an
anonymous function based on information gathered at run time.
This allows for greater flexibility, without too much extra coding.

The call can then be shortened to:

Finally, you can wrap it all into a single function as shown below.
Now the code’s starting to look more ‘readable’ which is a good
sign:

index firstname lastname age
Patricia Williams 7
Amanda Miller 18
Sarah Miller 24
Mary Johnson 25
Patrick Miller 27
James Brown 31
Michael Davis 43

We now have a simple generic function that can be used to sort any
associative array on a single scalar attribute.

Основные функции сортировки массива в PHP

Для сортировки массива в PHP вы можете использовать встроенные функции и . Разница между ними заключается в том, что сортирует массив в обратном порядке (по убыванию), а – в обычном порядке (по возрастанию).

Давайте посмотрим, как это работает. Отсортируем массив с помощью функции , прежде чем отобразить его содержимое. Код выглядит так:

<?php
sort($spisokTsvetov);
foreach ($spisokTsvetov as $key => $value) {
  echo '<p>' . $key . ' - ' . $value . '</p>';
}
?>

Результат будет следующим:

0 - black
1 - blue
2 - green
3 - red
4 - white

Как вы могли заметить, эта функция назначает новые ключи для элементов в массиве. Функция сортировки удаляет все существующие ключи, которые вы могли назначить, вместо того, чтобы просто переупорядочивать ключи. Решение этой проблемы рассмотрим позже.

Если вам нужен обратный порядок, единственное, что вам нужно сделать, это использовать вместо этого функцию , например, так:

<?php
rsort($spisokTsvetov);
foreach ($spisokTsvetov as $key => $value) {
  echo '<p>' . $key . ' - ' . $value . '</p>';
}
?>

И результат будет следующий:

0 - white
1 - red
2 - green
3 - blue
4 - black

Теперь давайте узнаем, как решить проблему с потерей ключей, что важно, если вы используете ассоциативные массивы

Сортировка ассоциативных массивов в PHP

Как мы видели ранее, функции и не подойдут, если нам нужно сохранить ключи нашего массива. К счастью, в PHP есть встроенные функции и для этой проблемы. Функции называются и . По примеру вышерассмотренных функций, сортирует по возрастанию, а – по убыванию. Кроме этого, данные функции поддерживают сохранение ключей массива. Итак, давайте посмотрим, как эти функции справляются с сортировкой данных в массиве. Повторим наш тест с использованием новых функций:

<?php
asort($spisokTsvetov);
foreach ($spisokTsvetov as $key => $value) {
  echo '<p>' . $key . ' - ' . $value . '</p>';
}
?>

Результат будет следующим:

night - black
sky - blue
grass - green
apple - red
wall - white

Теперь результат выглядит намного лучше. Чтобы получить сортировку в обратном порядке, просто используйте функцию вместо .

Но что делать, если вы хотите отсортировать ассоциированные массивы на основе ключей? Нет проблем, давайте посмотрим как это сделать.

Как сортировать массив по ключу в PHP

Вы уже вероятно догадались, что в PHP есть функция сортировки ассоциативного массива по ключам. Этими функциями являются и . Как и прежде, сортирует массив в обратном порядке. Использование такое же, как и раньше, поэтому код будет следующим:

<?php
ksort($spisokTsvetov);
foreach ($spisokTsvetov as $key => $value) {
  echo '<p>' . $key . ' - ' . $value . '</p>';
}
?>

Результат будет следующим:

apple - red
grass - green
night - black
sky - blue
wall - white

Использовать функцию довольно просто.

Помимо рассмотренных функций в PHP есть и другие, более сложные функции сортировки:

  • – сортировка нескольких или многомерных массивов.
  • – сортировка массива с использованием нечувствительного к регистру алгоритма «естественного порядка»
  • – сортировка массива с использованием алгоритма «естественного порядка».
  • – сортирует массив с помощью пользовательской функции сравнения и поддерживает связь с индексами.
  • – сортирует массив по ключам, используя пользовательскую функцию сравнения
  • – сортирует массив по значениям, используя пользовательскую функцию сравнения

Бонусный навык: поиск в массиве с помощью PHP

Представьте себе, что у вас есть большой массив, который заполняется из файла или кода. И вы не знаете, существует ли данное значение в массиве или нет. И если оно существует, то было бы хорошо получить ключ этого элемента.

Массив рассмотрим тот же (что в самом начале статьи).

Теперь, если вы хотите узнать, существует ли значение , вы можете использовать встроенную в PHP функцию . Ниже пример ее использования:

<?php
echo 'Blue is ' . array_search("blue", $spisokTsvetov);
?>

В результате вы получите следующее значение:

Blue is sky

На сегодня все, спасибо, что читаете нас!

  • 1348

  • 68

  • Опубликовано 09/12/2019

  • PHP, Уроки программирования

asort()- Sort Array in Ascending Order, According to Value

There is the following function sorts an associative array in ascending order, as per according to the value.
we will use simple examples where the values refer to girls’ age. therefore, here the values are numerical, then the PHP sort array will be sorted in that order.

<?php
$age = array(«Giselle»=>»25», «Amara»=>»15», «Josephine»=>»28», «Penelope»=>»18» );
asort($age);

foreach($age as $x => $x_value) {
print_r («Key=» . $x . «, Value=» . $x_value);
print_r («<br>»);
}
?>

1
2
3
4
5
6
7
8
9

<?php

$age=array(«Giselle»=>»25″,»Amara»=>»15″,»Josephine»=>»28″,»Penelope»=>»18»);

asort($age);

foreach($ageas$x=>$x_value){

print_r(«Key=».$x.», Value=».$x_value);

print_r(«<br>»);

}

?>

Output:

Key=Amara, Value=15
Key=Penelope, Value=18
Key=Giselle, Value=25
Key=Josephine, Value=28

1
2
3
4

Key=Amara,Value=15

Key=Penelope,Value=18

Key=Giselle,Value=25

Key=Josephine,Value=28

Introduction to the PHP usort() function

So far, you learned how to sort an array using a built-in comparison operator.

For example, when you use the function to sort an array of numbers, PHP uses the built-in comparison operator to compare the numbers.

To specify a custom comparison function for sorting, you use the function:

The function has two parameters:

  • is the input array.
  • is the custom comparison function.

The function returns on success or or failure.

The has the following syntax:

The function has two parameters which are the array elements to compare.

The function compares two elements ( and ) and returns an integer value:

  • zero (0) means is equal to .
  • a negative number means is before .
  • a positive number means is after .

ksort()- Sort Array in Ascending Order, According to Key

The is the following function that sorts an associative array in ascending order, as per according to the key:

<?php
$age = array(«Giselle»=>»25», «Amara»=>»15», «Josephine»=>»28», «Penelope»=>»18» );
ksort($age);

foreach($age as $x => $x_value) {
print_r («Key=» . $x . «, Value=» . $x_value);
print_r («<br>»);
}
?>

1
2
3
4
5
6
7
8
9

<?php

$age=array(«Giselle»=>»25″,»Amara»=>»15″,»Josephine»=>»28″,»Penelope»=>»18»);

ksort($age);

foreach($ageas$x=>$x_value){

print_r(«Key=».$x.», Value=».$x_value);

print_r(«<br>»);

}

?>

Output:

Key=Amara, Value=15
Key=Giselle, Value=25
Key=Josephine, Value=28
Key=Penelope, Value=18

1
2
3
4

Key=Amara,Value=15

Key=Giselle,Value=25

Key=Josephine,Value=28

Key=Penelope,Value=18

krsort()- Sort Array in Descending Order, According to Key

There is the following function sorts an associative array in descending order, as per according to the key.

<?php
$age = array(«Giselle»=>»25», «Amara»=>»15», «Josephine»=>»28», «Penelope»=>»18» );
krsort($age);

foreach($age as $x => $x_value) {
print_r («Key=» . $x . «, Value=» . $x_value);
print_r («<br>»);
}
?>

1
2
3
4
5
6
7
8
9

<?php

$age=array(«Giselle»=>»25″,»Amara»=>»15″,»Josephine»=>»28″,»Penelope»=>»18»);

krsort($age);

foreach($ageas$x=>$x_value){

print_r(«Key=».$x.», Value=».$x_value);

print_r(«<br>»);

}

?>

Output:

Key=Penelope, Value=18
Key=Josephine, Value=28
Key=Giselle, Value=25
Key=Amara, Value=15

1
2
3
4

Key=Penelope,Value=18

Key=Josephine,Value=28

Key=Giselle,Value=25

Key=Amara,Value=15

.

Important Note: The PHP Array asort() and arsort() function are used to PHP sort associative arrays by their value. The PHP array ksort() and krsort() function make PHP sort associative arrays, by their key.

arsort()- Sort Array in Descending Order, According to Value

Therefore, The following function is used to sorts an associative array in descending order, according to the value.

<?php
$age = array(«Giselle»=>»25», «Amara»=>»15», «Josephine»=>»28», «Penelope»=>»18» );
arsort($age);

foreach($age as $x => $x_value) {
print_r («Key=» . $x . «, Value=» . $x_value);
print_r («<br>»);
}
?>

1
2
3
4
5
6
7
8
9

<?php

$age=array(«Giselle»=>»25″,»Amara»=>»15″,»Josephine»=>»28″,»Penelope»=>»18»);

arsort($age);

foreach($ageas$x=>$x_value){

print_r(«Key=».$x.», Value=».$x_value);

print_r(«<br>»);

}

?>

Output:

Key=Josephine, Value=28
Key=Giselle, Value=25
Key=Penelope, Value=18
Key=Amara, Value=15

1
2
3
4

Key=Josephine,Value=28

Key=Giselle,Value=25

Key=Penelope,Value=18

Key=Amara,Value=15

Overview: PHP Sort Array

PHP has several functions which are deal with sorting arrays, and this functions to help sort it all out.There are the following main differences:

  • Some PHP sort Array based on the array keys, whereas others by the values, like as:
  • Whether or not the correlation between the keys and values is maintained after the sort, therefore, means the keys are reset numerically (0,1,2 …)
  • The order of the sort: alphabetical, low to high , high to low , natural, numerical, random, or user-defined
  • All of those functions act directly on the array variable itself, such as opposed to returning a new sorted array
  • If any of these kind sort functions evaluate two (2) members as equal then the order is undefined (means that the sorting is not stable).

Sorting on a single field

Sorting associative arrays is really quite simple — IF you know
beforehand which field you want to sort by. For example, to sort by
lastname you can use the usort (user-defined search) function:

The output is as follows:

index firstname lastname age
James Brown 31
Michael Davis 43
Mary Johnson 25
Amanda Miller 18
Sarah Miller 24
Patrick Miller 27
Patricia Williams 7

To sort by different fields just replace the
compare_lastname function with a function that orders by
firstname (see below), by age, or any other field in
the associative array. The strnatcmp («natural
order» string comparison) function is handy here as it can be
applied to numbers as well as strings.

Below we will explore using a single function to sort by different
fields by specifying the sort field in the function call. The
comparison function can also be generated on the fly as an anonymous
function.

A – Сортировка по оценке (параметр grade) (числовая сортировка)

Определим функцию для сортировки массива по оценке (параметр grade):

// Функция сортировки по оценке: сортировка по УБЫВАНИЮ.
function grade_sort($x, $y) {
    if ($x < $y) {
        return true;
    } else if ($x > $y) {
        return false;
    } else {
        return 0;
    }

}

Затем возьмем пользовательскую функцию и осуществим перебор двумерного массива PHP по первому ключу. Выглядит это примерно так:

// $students – наш многомерный массив, а grade_sort – созданная функция
usort ($students, ' grade_sort ');

Пример:

// Вызвать на печать массив в виде (начальный массив):
echo '<h2>Массив в виде</h2><pre>' . print_r($students, 1) . '</pre>';
// Сортировать по оценке (grade):
 uasort($students, 'grade_sort');
echo '<h2>Массив отсортирован по оценке</h2><pre>' . print_r($students, 1) . '</pre>';

PHP будет отправлять внутренние массивы к этой функции для дальнейшей сортировки. Если вам интересно, как все это происходит в деталях, то выведите на экран результаты сравнения значений внутри функции. А саму функцию после PHP создания двумерного массива измените следующим образом:

function grade_sort($x, $y) {
    static $count = 1;
    echo “<p>Iteration $count: {$x} vs. {$y} </p> n”;
    $count++;
    if ($x < $y) {
    return true;
    } else if ($x > $y) {
    return false;
    } else {
    return 0;
    }
}

Выводя на экран значения $x и $y , можно увидеть, как вызывается функция сортировки, определенная пользователем.

Можно сократить функцию grade_sort следующим образом:

// Функция числовой сортировки по оценке: сортировка по УБЫВАНИЮ
 function grade_sort($x, $y) {
    return ($x < $y);
}

Результаты сортировки двумерного массива PHP по оценке отображены на картинке ниже:

Примечание: Функция usort () сортирует по значениям, но не сохраняет ключи (для внешнего массива). Если ключи нужны, то лучше использовать функцию uasort ().

B – Сортировка по имени (в алфавитном порядке)

Чтобы отсортировать массив $students по первому ключу, необходимо сравнить две строки. Поэтому в примере с сортировкой в алфавитном порядке воспользуемся функция strcasecmp() (не чувствительна к регистру) и strcmp() (чувствительна к регистру). Получившийся двумерный массив PHP будет иметь следующий вид:

// Функция сортировки по имени:
function name_sort($x, $y) {
return strcasecmp($x, $y);
}

Пример:

// Вывести на печать массив в виде (начальный массив):
echo '<h2>Массив в виде</h2><pre>' . print_r($students, 1) . '</pre>';
// Сортировка по имени:
 uasort($students, 'name_sort');
echo '<h2>Массив отсортирован по имени</h2><pre>' . print_r($students, 1) . '</pre>';

На скриншоте, приведенном ниже, показан результат сортировки по имени:

Пожалуйста, оставьте ваши отзывы по текущей теме статьи. Мы крайне благодарны вам за ваши комментарии, отклики, дизлайки, лайки, подписки!

Пожалуйста, оставьте ваши мнения по текущей теме материала. Мы очень благодарим вас за ваши комментарии, дизлайки, отклики, лайки, подписки!

ОСОльга Сайфудиноваавтор статьи «Sorting multi-dimensional array in PHP»

PHP usort() function examples

Let’s take some examples of using the function.

1) Using the PHP usort() function to sort an array of numbers

The following example illustrates how to use the function to sort an array of numbers:

Output:

How it works.

  • First, define an array of three numbers 2, 1, and 3.
  • Second, use the function to sort the array. The callback function returns 0 if two numbers are equal, -1 if the first number is less than the second one, and 1 if the first number is greater than the second one.

To sort the elements of the array in descending order, you just need to change the logic in the comparison function like this:

If you use PHP 7 or newer, you can use the spaceship operator () to make the code more concise:

The spaceship operator compares two expressions and returns -1, 0, or 1 when is respectively less than, equal to, or greater than . For example:

If the callback is simple, you can use an arrow function like this:

Note that PHP introduced the arrow functions since PHP 7.4.

2) Using the PHP usort() function to sort an array of strings by length

The following example uses the function to sort an array of names by length:

Output:

3) Using the PHP usort() function to sort an array of objects

The following example uses the function to sort an array of objects by the property.

Output:

How it works.

  • First, define a class that has two properties: and .
  • Second, define the array that holds the objects.
  • Third, use the function to sort the objects of the array. The function uses a comparison function that compares the age of two objects.

If you want to sort the objects by name, you can compare the in the comparison like this:

Using a static method as a callback

The following example uses a static method of class as a callback for the function:

In this example, we define the class that contains the static method.

The static method compares two objects by age using the spaceship operator.

To use the static method of the class as the callback the function, you pass an array that contains two elements:

The first element is the class name and the second one is the static method.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector