정렬은 배열의 요소를 특정 순서로 정렬하는 것입니다. PHP는 숫자 배열과 같은 일반 배열과 연관 배열에 대해 정렬을 수행합니다. 숫자형 배열과 같은 일반 배열은 간단한 sort() 함수를 사용하여 정렬할 수 있으며, 연관 배열에 대해 정렬을 수행하는 다양한 함수가 있습니다.
광고 이 카테고리에서 인기 있는 강좌 PHP 개발자 - 전문 분야 | 8개 코스 시리즈 | 3가지 모의고사무료 소프트웨어 개발 과정 시작
웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등
정렬은 오름차순 또는 내림차순, 알파벳 또는 숫자 순서, 자연순, 무작위 및 사용자 정의 순서로 수행할 수 있습니다. 숫자 배열이나 색인 배열과 같은 배열과 연관 배열의 경우 키를 기준으로 오름차순이나 내림차순 배열로 정렬이 수행되거나 오름차순이나 내림차순과 같은 두 가지 순서의 값을 기준으로 정렬이 수행됩니다. 배열을 정렬하면 데이터 요소가 정렬된 형식인 경우 검색이 더 쉬워집니다.
정렬 기능을 사용하여 PHP에서 정렬이 수행됩니다. 다양한 정렬 기능이 있습니다.
연공서열에 따라 가족 구성원의 나이를 알고 싶다고 가정해 보겠습니다. 한 가족에는 15명의 구성원이 있을 수 있습니다. 15명의 멤버들의 나이를 정렬하기 위해 정렬 기능을 사용하여 빠르게 결과를 얻어냅니다. 따라서 그러한 경우에는 sort가 중요하며 바람직합니다.
그리고 라이브러리를 사용할 필요도 없습니다.
구문:
sort(array);
여기서 배열은 입력 배열의 이름입니다.
다음 예에서는 $people 및 $ages 배열의 요소를 정렬합니다.
가나다순 정렬:
$people = array ('Rama', 'James', 'Mary', 'Alice', 'Radha');
숫자순으로 정렬:
$ages = array (25,10,30,15,20);
위의 두 배열을 결합하여 하나의 연관을 만듭니다.
$people_ages = array ('James' => 25, 'Rama' => 10, 'Mary' => 30, 'Alice' => 15, 'Radha' => 20);
예를 들어 숫자순으로 정렬:
코드:
<?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>"; } ?>
출력 :
알파벳순으로 정렬 예:
코드:
<?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>"; } ?>
출력 :
키-값 쌍 연관이 있는 연관 배열에 대해 정렬을 수행하면 결국 키가 손실됩니다. 또한 정렬이 수행되었지만 이제 배열의 각 요소에 새로운 숫자 인덱스가 할당되었습니다.
코드:
// 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>"; }
출력:
따라서 단순한 sort() 대신 asort()를 사용합니다. asort()는 연관 배열의 요소를 오름차순으로 정렬하는 함수입니다. 그리고 arsort()는 배열의 요소를 내림차순으로 정렬하는 함수입니다. 둘 다 값을 기준으로 정렬됩니다. 이제 다른 배열 기능과 함께 이러한 배열에 대해 자세히 알아 보겠습니다.
아래에는 다양한 유형의 배열 함수가 언급되어 있으며, 정렬 순서는 오름차순인지 내림차순인지, 키 기준 또는 값 기준 정렬 기능도 언급되어 있습니다.
Let us learn about each function in detail
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>"; }
Output:
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>"; }
Output :
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>"; }
Output:
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>"; }
Output:
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>"; }
Output:
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>"; }
Output:
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>"; }
Output:
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>"; } ?>
Output :
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>"; }
Output :
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>"; }
Output :
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>"; }
Output:
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>"; }
Output :
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>"; }
Output:
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.
위 내용은 PHP로 정렬하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!