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

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

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

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

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

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

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.

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)

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

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

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

Adblock
detector