Tri en PHP

WBOY
Libérer: 2024-08-29 13:04:46
original
306 Les gens l'ont consulté

Le tri consiste à organiser les éléments d'un tableau dans un ordre particulier. PHP effectue un tri sur des tableaux normaux comme un tableau numérique et sur des tableaux associatifs. Les tableaux normaux comme les tableaux numériques peuvent être triés en utilisant la simple fonction sort(), et pour effectuer le tri sur le tableau associatif, nous avons différentes fonctions.

PUBLICITÉ Cours populaire dans cette catégorie DEVELOPPEUR PHP - Spécialisation | Série de 8 cours | 3 tests simulés

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

Le tri peut être effectué par ordre croissant ou décroissant, par ordre alphabétique ou numérique, de manière naturelle, aléatoire et également par ordre défini par l'utilisateur. Pour les tableaux tels que le tableau numérique ou le tableau indexé et pour les tableaux associatifs, le tri est effectué par ordre croissant ou décroissant en fonction de la clé ou en fonction de la valeur dans l'un des deux ordres, comme l'ordre croissant ou décroissant. Le tri sur des tableaux facilite votre recherche si les éléments de données sont sous forme triée.

Comment le tri s'effectue-t-il en PHP ?

Le tri est effectué en PHP à l'aide de fonctions de tri. Il existe une variété de fonctions de tri.

Supposons que vous vouliez connaître l'âge des membres d'une famille en fonction de l'ancienneté. Il peut y avoir 15 membres dans une famille. Pour trier l'âge de 15 membres, nous utilisons la fonction de tri et obtenons le résultat rapidement. Ainsi, dans un tel cas, le tri entre en jeu et est préférable.

De plus, il n'est pas nécessaire d'utiliser des bibliothèques.

Syntaxe :

sort(array);
Copier après la connexion

où un tableau est le nom du tableau d'entrée.

L'exemple suivant trie les éléments du tableau $people et $ages.

Trier par ordre alphabétique :

$people = array ('Rama', 'James', 'Mary', 'Alice', 'Radha');
Copier après la connexion

Trier par ordre numérique :

$ages = array (25,10,30,15,20);
Copier après la connexion

Combiner les deux tableaux ci-dessus et créer un associatif.

$people_ages = array ('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
Copier après la connexion

Trier par ordre numérique avec exemple :

Code :

<?php
//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
} ?>
Copier après la connexion

Sortie :

Tri en PHP

Trier par ordre alphabétique avec exemple :

Code :

<?php
//example to perform people array
$people= array('Rama', 'James', 'Mary', 'Alice', 'Radha');
// calculate length of array
$array_length = count($people);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($people);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i]."<br>";
}
?>
Copier après la connexion

Sortie :

Tri en PHP

Tri d'un tableau associatif

Effectuer un tri sur des tableaux associatifs qui ont une association de paires clé-valeur entraînera la perte des clés. De plus, bien que le tri soit effectué, chaque élément du tableau se voit désormais attribuer un nouvel index numérique.

Code :

// example to perform sort on people and ages array together
// you will find that the keys are not preserved and changed
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting we will use foreach loop
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach ($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Sortie :

Tri en PHP

Et ainsi, au lieu d'un simple sort(), nous utilisons asort(). asort() est une fonction qui trie les éléments d'un tableau associatif par ordre croissant. Et arsort() est une fonction qui trie les éléments d'un tableau par ordre décroissant. Les deux sont triés par valeur. Découvrons maintenant ces tableaux ainsi que d'autres fonctions de tableau en détail

Types de tri en PHP

Les différents types de fonctions de tableau sont mentionnés ci-dessous, ainsi que l'ordre de tri, qu'il soit croissant ou décroissant et la fonction trie par clé ou par valeur sont également mentionnés.

  • sort(): this function sorts the input array in ascending order and sorts it by value
  • rsort(): this function sorts the input array in descending order and sorts it by value
  • asort(): this function sorts the input array in ascending order and sorts it by value
  • arsort(): this function sorts the input array in descending order and sorts by value
  • ksort(): this function sorts the input array in ascending order and sorts it by key
  • krsort(): this function sorts the input array in descending order and sorts it by key
  • usort(): this function sorts the input array based on the user-defined function and sorts by value
  • uasort(): this function sorts the input array based on the user-defined function and sorts by value
  • uksort(): this function sorts the input array based on the user-defined function and sorts by key
  • natsort(): this function sorts the input array-based natural ordering.
  • natcasesort(): this function sorts the input array-based natural ordering and is case insensitive.
  • shuffle(): this function sorts the input array based on the value, and the output is a random order of values.

Let us learn about each function in detail

1. sort()

This function we have already seen. This function performs sorting on the given array and arranges the elements of the array in ascending array.

Code :

//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
sort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}
Copier après la connexion

Output:

Tri en PHP

2. rsort()

This function performs sorting on the given array and arranges the elements of the array in descending array, opposite of what sort() function does. Also, the sorting is performed with values.

a. Code:

//example to perform ages array
$ages = array(25,10,30,15,20);
// calculate length of array
$array_length = count($ages);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i] ."<br>";
}
echo '<hr>';
//performing sort
rsort($ages);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $ages[$i]."<br>";
}
Copier après la connexion

Output :

Tri en PHP

b. Code:

//example to perform people array
$people= array('Rama', 'James', 'Mary', 'Alice', 'Radha');
// calculate length of array
$array_length = count($people);
echo "Before Sort"."<br>";
//array before sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i] ."<br>";
}
echo '<hr>';
//performing sort
rsort($people);
echo "After Sort"."<br>";
//array after sorting
for($i=0;$i<$array_length;$i++)
{
echo $people[$i]."<br>";
}
Copier après la connexion

Output:

Tri en PHP

3. asort()

This function performs sorting on the given array and arranges the array’s values in ascending order, opposite of what sort() function does. Also, the sorting is performed with values and not keys.

Code :

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
asort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output:

Tri en PHP

4. arsort()

This function performs sorting on the given array and arranges the array’s values in a descending array. This example prints the array using a foreach loop and outputs the result as before sorting and after sorting.

Code:

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
arsort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output:

Tri en PHP

5. ksort()

This function performs sorting on the given array and arranges the keys of the array in ascending order. This example prints the array using a foreach loop and outputs the result as before sorting and after sorting.

Code:

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
ksort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output:

Tri en PHP

6. krsort()

This function performs sorting on the given array and arranges the keys of the array in descending order. This example prints the array using a foreach loop and outputs the result as before sorting and after sorting.

Code:

//example to perform people_ages array
$people_ages = array('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
// calculate length of array
$array_length = count($people_ages);
echo "Before Sort"."<br>";
//array before sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
krsort($people_ages);
echo "After Sort"."<br>";
//array after sorting
foreach($people_ages as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output:

Tri en PHP

7. natsort()

This function performs sorting on the given array and arranges the keys of the array in descending order. This example prints the array using a foreach loop and outputs the result as before sorting using assort() function and after sorting using natsort() function.

This function refreshes the output as the function randomizes the order of values in the given array. New numeric keys replace the keys mentioned in the array are assigned. For example, 10 is greater than 7 in a human being view, but according to the sorting algorithm 10 comes before 7.

We will use the natural flow of order.

Code:

<?php
$input = array("13 orange","14 Apple","15 3Banana","11 papaya","10 Grapes");;
$arr1 = $arr2 = $input;
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($arr1);
echo "Using asort function "."<br>";
//array before sorting
foreach($arr1 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
natsort($arr2);
echo "Using natsort function "."<br>";
foreach($arr2 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
?>
Copier après la connexion

Output :

Tri en PHP

8. natcasesort()

This function works the same as natsort() but is case insensitive.

Code:

$input = array("13 orange","14 Apple","15 Banana","11 papaya","10 Grapes");;
$arr1 = $arr2 = $input;
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
sort($arr1);
echo "Using asort function "."<br>";
//array before sorting
foreach($arr1 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
//performing sort
natcasesort($arr2);
echo "Using natcasesort function "."<br>";
foreach($arr2 as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output :

Tri en PHP

9. usort()

This function performs sorting on the given array and arranges the values of the array in ascending order. This example prints the array using for loop and outputs the result.

In this program, the usort function takes two parameters: the input array and the other is the name of the function being called (here is compare).

This compare function is user-defined; also, the function is optional. This function returns 0 only if the condition in if block is satisfied, and else it will send -1 if the values compared is smaller than the other and 1 if the values compared is greater than the other.

Code:

function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
$numbers = array(10,4,5,3,20);
echo "Before Sort"."<br>";
//array after sorting
$array_length = count($numbers);
for($i=0;$i<$array_length;$i++)
{
echo $numbers[$i]."<br>";
}
echo '<hr>';
//performing sort
usort($numbers, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($numbers);
for($i=0;$i<$array_length;$i++)
{
echo $numbers[$i]."<br>";
}
Copier après la connexion

Output :

Tri en PHP

10. uasort()

This function performs sorting on the given array and arranges the array’s values in ascending order using the compare function.

Code:

<?php
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
echo '<hr>';
//performing sort
$input = array("num1"=>10,"num2"=>4,"num3"=>3,"num4"=>5, "num5"=>20);
uasort($input, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output:

Tri en PHP

11. uksort()

This function performs sorting on the given array and arranges the array’s keys in ascending order using the compare function.

Code:

<?php
function compare($x, $y) {
if($x == $y ){
return 0;
}
if($x < $y ){
return -1;
}
if($x > $y ){
return 1;
}
}
echo '<hr>';
//performing sort
$input = array("num1"=>10,"num2"=>4,"num3"=>3,"num4"=>5, "num5"=>20);
uksort($input, "compare");
echo "After Sort"."<br>";
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output :

Tri en PHP

12. shuffle()

This function refreshes the output as the function randomizes the order of values in the given array. New numeric keys replace the keys mentioned in the array are assigned.

Code:

$input = array('a'=>"Guava",'e'=>"Apple",'b'=>"Orange",'c'=>"Papaya", 'd' => "Banana");
echo "Before Sort"."<br>";
//array before sorting
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
echo '<hr>';
shuffle($input);
echo 'You need to refresh to see the new shuffle everytime'.'<br>';
$array_length = count($input);
echo '<hr>';
//array after sorting
$array_length = count($input);
foreach($input as $key=>$value)
{
echo $key."=>".$value."<br>";
}
Copier après la connexion

Output:

Tri en PHP

Conclusion

In this article, most of the types of sorting are covered. The arrays are explained with examples. I hope you find it useful, informative and interesting.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
php
source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!