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

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

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

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)

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

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)

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().

Она будет принимать два аргумента. Первый аргумент – это наш массив; второй аргумент – будет содержать имя функции, сравнивающей два элемента.

Функция сравнения будет принимать две переменные и должна возвращать одно из значений:

1 – если первый элемент сравнения больше второго;

-1 – если второй больше первого;

0 – если элементы равны.

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

Для этого сначала объявим сам массив, который будет содержать строковые элементы различной длины.

Далее создадим пользовательскую функцию, которая будет принимать две переменные и сравнивать их длины, а в результате сравнения будет возвращать одно из значений: 1, -1 или 0.

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

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

<?
$Mass = array('Андрей', 'Яна', 'Катя');
function check_length($str1,$str2){
$length1 = strlen($str1);
$length2 = strlen($str2);
if($length1 == $length2):
return 0;
elseif($length1 < $length2):
return -1;
else:
return 1;
endif;	
}
usort($Mass,"check_length");
print_r($Mass);
?>

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

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

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

<?
$Mass='яна';
$Mass='андрей';
$Mass='катя';
function check_length($str1,$str2){
$length1 = strlen($str1);
$length2 = strlen($str2);
if($length1 == $length2):
return 0;
elseif($length1 < $length2):
return -1;
else:
return 1;
endif;	
}
uksort($Mass,"check_length");
print_r($Mass);
?>

Ключи элементов массива отсортированы по возрастанию их длины.

И также мы можем создать пользовательскую сортировку ассоциативного массива по значениям его элементов. В этом нам поможет функция uasort().

Принцип все тот же.

<?
$Mass='яна';
$Mass='андрей';
$Mass='катя';
function check_length($str1,$str2){
$length1 = strlen($str1);
$length2 = strlen($str2);
if($length1 == $length2):
return 0;
elseif($length1 < $length2):
return -1;
else:
return 1;
endif;	
}
uasort($Mass,"check_length");
print_r($Mass);
?>

Теперь массив отсортирован по увеличению длин его значений.

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

Чтобы хорошенько понять, как работает пользовательская сортировка, нужно попрактиковаться и попробовать написать какую-то свою функцию сравнения.

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

Практикуйтесь, пишите Ваши комментарии и делитесь статьей с друзьями при помощи кнопок социальных сетей.

Если Вы еще не подписаны на обновления блога, то подписывайтесь. Форма подписки находится ниже.

С Вами была Анна Котельникова. До встречи в следующих статьях.

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.

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).
Добавить комментарий

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

Adblock
detector