Multi-dimensional array and one-dimensional array in php array sorting

Source: Internet
Author: User

We know that php arrays are divided into multi-dimensional arrays and one-dimensional arrays. Next we will introduce the principles and implementation methods of sorting php multi-dimensional arrays and one-dimensional arrays respectively.

One-dimensional array

Group 1: sort and rsort, which are sorted by asc and desc in the order of PHP array key values, at the same time, the index relationship of the original array is damaged-in fact, after the index is deleted, the number index starting from 0 is re-created. Take a look at the routine:

The Code is as follows: Copy code
<? Php
$ A = array ("a" => 1, 2 );
Sort ($ );
Var_dump ($ );
 
Rsort ($ );
Var_dump ($ );
?>
Let's take a look at the first output result, and the first output:
Array (2 ){
[0] =>
Int (1)
[1] =>
Int (2)
}
Second output:
Array (2 ){
[0] =>
Int (5)
[1] =>
Int (4)
}

Where did we find that index a was not defined? Where are you going? It is certain that they have been relentlessly deleted. If you don't care about the original index relationship, you can use them!

The second group of functions: asort and arsort. These two functions are more powerful. As long as they can retain the original index relationship of the array, replace the sort and rsort functions in the above example with the two functions respectively, view the running result:

The Code is as follows: Copy code
Array (2 ){
["A"] =>
Int (1)
[0] =>
Int (2)
}
Array (2 ){
[0] =>
Int (2)
["A"] =>
Int (1)
}

You can understand it at a glance!

The third group of PHP array sorting functions: krsort and ksort are different from the above two groups. These two functions sort key names. You can replace the functions in the above example with the two, let's take a look at the specific running results. Otherwise, this article will be written too long. I'm afraid some of my brothers will not be patient enough to see the focus of this article, although the focus is below!

Sort PHP arrays by using custom functions. The following three functions are available:
Uasort sorts the key values of the PHP Array Using a custom function and retains the original index relationship.
Uksort sorts the key names of PHP arrays by using a custom function and retains the original index relationship.
Usort sorts the key values of the PHP array through a user-defined function, deletes the original index relationship, and creates a new index from scratch.

An example is required:

The Code is as follows: Copy code
<! -- P
// Start with a function. This function requires two parameters and the return value is certain.
// If the first parameter is equal to the second parameter, 0 is returned. If the value is smaller than the second parameter,-1 is returned. If the value is greater than the second parameter, 1 is returned.
 
Function cmp ($ a, $ B ){
$ A + = 1;
$ B + = 3; // change these values and compare them.
 
If ($ a = $ B) return 0;
Return ($ a & lt; $ B )? -1:1;
}
 
$ A = array (1, 4, 3, 5 );
Uasort ($ a, 'cmp ');
Var_dump ($ );
-->
Output result:
Array (4 ){
[0] =>
Int (1)
[3] =>
Int (5)
[1] =>
Int (4)
[2] =>
Int (3)
}

,

Multi-dimensional array sorting


For example, array_multisort ($ a, $ B), $ a, and $ B are two arrays. After sorting, the 3rd elements in the $ a array are ranked first, then, the third element of $ B is ranked first regardless of its size in $ B. Check the program running result below:

The Code is as follows: Copy code

<? Php
$ A = array (100,80, 50,10, 0 );
$ B = array ("c", "f", "q", "e", "z ");
Array_multisort ($ a, $ B );
Var_dump ($ );
Var_dump ($ B );
?>
Running result:
Array (5) {[0] => int (0) [1] => int (10) [2] => int (50) [3] = & gt; int (80) [4] = & gt; int (100 )}
Array (5) {[0] => string (1) "z" [1] => string (1) "e" [2] => string (1) "q" [3] => string (1) "f" [4] => string (1) "c "}

Obviously, the z of the fifth element of array B is ranked first!

In fact, it turns out that array_multisort () First sorts the first array by the size of the key value, then the other arrays are adjusted according to the adjustment policy of the first array -- put the third element in the first place, and put the second element in the second place ...... -- In fact, the most basic embodiment of this multi-dimensional array Sorting Algorithm!

Note that the number of elements in the two arrays must be the same. Otherwise, a warning message is displayed:
Warning: array_multisort () [function. array-multisort]: Array sizes are inconsistent in ......

Well, I hope you can use the above. Let's talk about the main thing: array_multisort () sorts multi-dimensional arrays. This function will be very useful for future projects!

First, let's take a look at the operation method for sorting each element of the multi-dimensional array [array], which is very simple, but there are several parameters to describe, if you have some knowledge about SQL, you will understand it at a Glance:

The Code is as follows: Copy code
<? Php
// Let's construct a multi-dimensional array
$ A = array (, 2, 7 );
$ B = array ('AB', 'ac', 'ad', 'ag', 'ap ');
 
$ AB = array ($ a, $ B );
// Start sorting
Array_multisort ($ AB [0], SORT_NUMERIC, SORT_DESC, $ AB [1], SORT_STRING, SORT_ASC );
Print_r ($ AB );
?>

Note: First, we use SORT_NUMERIC to declare that the $ AB [0] is sorted by numerical type, and SORT_DESC is used.
The declared order is in reverse order (from large to small), and then we sort $ AB [1] In string type. The order is in ascending order (order)
The sorting result of the last array $ AB is a combination of the two. First, sort the result in the reverse order of $ AB [0, if $ AB [0] contains values of the same size, the values are arranged in the order of $ AB [1]. The output result is as follows:

Array (
[0] => Array ([0] => 100 [1] => 7 [2] => 7 [3] => 4 [4] => 2)
[1] => Array ([0] => AB [1] => ag [2] => ap [3] => ad [4] => ac)
)
Is it similar to using order by in a database? Actually, it's almost the same!

Now let's look at a more practical example:

The Code is as follows: Copy code
<? Php
$ Array [] = array ("age" => 20, "name" => "li ");
$ Array [] = array ("age" => 21, "name" => "ai ");
$ Array [] = array ("age" => 20, "name" => "ci ");
$ Array [] = array ("age" => 22, "name" => "di ");
 
Foreach ($ array as $ key => $ value ){
$ Age [$ key] = $ value ['age'];
$ Name [$ key] = $ value ['name'];
}
 
Array_multisort ($ age, SORT_NUMERIC, SORT_DESC, $ name, SORT_STRING, SORT_ASC, $ array );
Print_r ($ array );
?>

In this example, the $ array [] array is constructed based on the records read from the database. We now arrange them in the order of age, if they are of the same age, they are sorted by names. This sort will be frequently used in the future,
Because the sorting parameter required by array_multisort () must be a column, we use foreach to read the age and name of this array. after that?
As in the preceding example, sort the array. the last $ array parameter must be sorted, because the two front parameters have no relationship with the PHP array to be sorted in form, although they are actually the data in $ array -- the columns we extract from $ array -- sorting of course requires columns, we haven't seen sorting with row data yet!

The output result is as follows:

The Code is as follows: Copy code
Array (
[0] => Array ([age] => 22 [name] => di)
[1] => Array ([age] => 21 [name] => ai)
[2] => Array ([age] => 20 [name] => ci)
[3] => Array ([age] => 20 [name] => li)
)

As you can see, it's actually quite simple, that is, the several parameters that need to be capitalized are a little annoying! Although it is a bit difficult to understand, but it is good to understand, it will be very useful in the future!
Appendix:
Sort order mark:

SORT_ASC-sort by Ascending Order
SORT_DESC-sort by descent

Sorting type flag:

SORT_REGULAR-compare projects by common methods
SORT_NUMERIC-compare projects by numerical values
SORT_STRING-compare items by string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.