PHP simple array Sorting method for everyone to learn the reference.
PHP does not know how to compare two arrays and needs to create a way to compare them.
First, the initialization of the numeric index array
Copy the Code code as follows:
$arr = Array (' 100 ', ' 200 ', ' 300 ');
The code above creates an array with 3 values. The numeric index of the PHP array starts at 0. So the value of $arr[0] is 100.
You can copy the values in one array into another array with a simple "=" sign.
If you need to save ascending numbers in an array, you can use the range () function to create the array automatically.
The following code creates an array of numbers from 1 to 10:
Copy the Code code as follows:
$nums = range (1,10);
This function also has a third parameter that allows you to set the step size of the number growth. For example: Range (1,10,2) is an odd number between 1 and 10.
PHP also supports related arrays, that is, you can associate variable values with keywords. Such as:
Copy the Code code as follows:
$arr = Array (' One ' =>100, ' =>200 ', ' three ' =>300);
Second, array sorting
1. Sort () Function: Sort alphabetically by array value or ascending by number.
The sort () function is case-sensitive and all uppercase letters are preceded by lowercase letters. This function also has a second parameter that can be passed sort_numeric or sort_string or sort_regular (the default). It is useful to specify the sorting function, for example, when the demon compares the numbers 12 and 2 o'clock, from the string, 12 is less than 2, and the opposite is the digital angle.
2, Asort () function, Ksort () function:
If a related array is used, the sorting of keywords and values remains consistent after sorting. We're going to use these two functions. Ksort are sorted by key (keyword), and asort is the value (in ascending order).
For example, there are arrays:
$price = Array (' apple ' = 5, ' banana ' = 6, ' lychee ' =7);
We use Ksort ($price); After sorting the result is: Lychee--7, Apple--5, Banana--6
With Asort ($price); sorted by: Apple--5, Banana--6, lychee--7
The corresponding inverse sequence is to add an ' r ' to the sort front. namely Rsort (), Arsort (), Krsort ()
Third, the sorting of multidimensional arrays
PHP knows how to compare two numbers or strings, but each element of a multidimensional array is an array.
PHP does not know how to compare two arrays, so you need to create a way to compare them.
The above describes the ancient four brothers from the big to the small ranking of the order of PHP simple array implementation code, including the Ancients four brothers from the big to the small ranking of the content, I hope that the PHP tutorial interested in a friend helpful.