PHP knows how to compare two numbers or strings, but each element of a multi-dimensional array is an array. PHP does not know how to compare two arrays, so it is necessary to establish a method to compare them. Php simple array sorting method for your reference.
PHP does not know how to compare two arrays. you need to create a method to compare them.
I. initialization of the numeric index array
The code is as follows:
$ Arr = array ('20140901', '20160901', '20160901 ');
The code above creates an array with three values. The numeric index of the PHP array starts from 0. Therefore, the value of $ arr [0] is 100.
You can use a simple "=" to copy the values in an array to another array.
To save numbers in ascending order to an array, you can use the range () function to automatically create this array.
The following code creates an array of numbers from 1 to 10:
The code is as follows:
$ Nums = range (1, 10 );
This function has a third parameter, which can be used to set the step size for numerical 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. For example:
The code is as follows:
$ Arr = array ('one' => 100, 'two' => 200, 'Three '=> 300 );
II. array sorting
1. sort () function: sort by letters or numbers of array values in ascending order.
The sort () function is case-sensitive. all uppercase letters are in front of lowercase letters. This function also has a second parameter, which can be passed SORT_NUMERIC, SORT_STRING or SORT_REGULAR (default ). It is very useful to specify the sorting function. for example, when the number 12 and 2 are compared to the number 12, the number 12 is smaller than 2, and the number is the opposite.
2. asort () function, ksort () function:
If related arrays are used, the sorting of keywords and values must be consistent after sorting. These two functions are required. Ksort is sort by key (keyword), and asort is sort by value (by value) (both in ascending order ).
For example, there is an array:
$ Price = array ('apple' = 5, 'banana '= 6, 'lychee' = 7 );
We use ksort ($ price); the sorting result is lychee -- 7, Apple -- 5, and banana -- 6.
The sorting result with asort ($ price) is: Apple -- 5, banana -- 6, lychee -- 7
The corresponding reverse sorting is to add a 'R' before the sort '. That is, rsort (), arsort (), krsort ()
3. multi-dimensional array sorting
PHP knows how to compare two numbers or strings, but each element of a multi-dimensional array is an array.
PHP does not know how to compare two arrays, so it is necessary to establish a method to compare them.