How to sort PHP multidimensional arrays

Source: Internet
Author: User
Tags foreach array sort mixed php code sorted by name strlen


For example, I have a multidimensional array $relationshop_list, which has IDs, with sort two columns, and I want the array to be sorted in descending order of ID, sorted in sort of way:
Sort
$array _field = Array_column ($relationshop _list, ' sort '); Bring up the Sort column
$array _id = Array_column ($relationshop _list, ' id '); Submit ID Column
Array_multisort ($array _field,sort_desc, $array _id,sort_desc, $relationshop _list);

Note: Array_column is the new method of php5.5

Array_multisort method implementation, but if it is a multidimensional array, and we want to specify a field in the array to sort, then we need to write our own method implementation. This article shares the code for a multidimensional array sort method for a PHP-specified field that can be sorted by the array of field fields.

Function Sortarrbyfield (& $array, $field, $desc = False) {
$FIELDARR = Array ();
foreach ($array as $k => $v) {
$FIELDARR [$k] = $v [$field];
}
$sort = $desc = = False? Sort_asc:sort_desc;
Array_multisort ($FIELDARR, $sort, $array);
}

array_multisort-to sort multiple arrays or multidimensional arrays
Description
BOOL Array_multisort (array ar1 [, mixed arg [, mixed ... [, array ...]] )

Array_multisort
(PHP 4, PHP 5)
Returns TRUE if successful, and returns FALSE if it fails.

Array_multisort () can be used to sort multiple arrays at once, or to sort multidimensional arrays based on one dimension or multidimensional.

The association (string) key name remains unchanged, but the numeric key name is indexed.

The input array is treated as a column of a table and sorted by row?? This is similar to the function of the SQL ORDER BY clause. The first array is the primary array to sort. The rows (values) in the array are the same, sorted by the size of the corresponding values in the next input array, and so on.

The parameter structure of this function is somewhat unusual, but very flexible. The first argument must be an array. Each of the next parameters can be an array or a sort flag listed below.

Sort order Flags:


sort_asc– Sorted by ascending order

sort_desc– Sorted in descending order
Sort Type Flags:
sort_regular– items are compared in the usual way

sort_numeric– the project by numerical comparison

sort_string– items by string comparison
You cannot specify two similar sort flags after each array. The sort flags specified after each array are valid only for the array-the default value SORT_ASC and Sort_regular before that.


Simple Sort


First, let's look at the simplest scenario: simply sort an array element from low to high, which can be arranged either numerically or alphabetically. The sort () function of PHP implements this function, as shown in listing a:
Listing A
<?php
 $data = Array (5,8,1,7,2);
Âsort ($data);
Âprint_r ($data);
Â?>
The output results are as follows:
Array ([0] => 1
[1] => 2
[2] => 5
[3] => 7
[4] => 8
)
You can also sort using the Rsort () function, which results in the opposite of the sort () simple sort result used earlier. The Rsort () function is inverted from highest to lowest on an array of elements, and can also be arranged alphabetically by number size. Listing B shows us an example of it:
Listing B
<?php $data = Array (5,8,1,7,2); Rsort ($data); Print_r ($data);
?>
Its output results are as follows:
Array ([0] => 8
[1] => 7
[2] => 5
[3] => 2
[4] => 1
)
Sort by keyword
When we use arrays, we often reorder them according to the array of keywords, from high to low. The Ksort () function is the sort of function that is sorted by keyword, and it maintains the relevance of the keyword in the ordering process. Listing C is an example:
Listing C
<?php $data = Array ("US" => "United States", "in" => "India", "DE" => "Germany", "ES" => "Spain"); Ksort ($da TA); Print_r ($data);
?>
Its output results are as follows:
Array ([DE] => Germany
[ES] => Spain
[In] => India
[US] => United States
)
The Krsort () function is inverted according to the array of keywords, Listing D is an example of this:
Listing D
<?php $data = Array ("US" => "United States", "in" => "India", "DE" => "Germany", "ES" => "Spain"); Krsort ($d ATA); Print_r ($data);
?>
Its output results are as follows:
Array ([US] => United States
[In] => India
[ES] => Spain
[DE] => Germany
)
Sort by value
If you want to use value ordering instead of keyword sorting, PHP can also meet your requirements. You can just use the Asort () function instead of the Ksort () function you mentioned earlier. As shown in Listing E:
Listing E
<?php $data = Array ("US" => "United States", "in" => "India", "DE" => "Germany", "ES" => "Spain"); Asort ($da TA); Print_r ($data);
?>
The following is the output of the result. Note that this result differs from the results of the above using the Ksort () function-both of which are sorted alphabetically, but they are sorted according to the different fields of the array.
Also, note that the relationship between the keyword-values is always maintained; it's just a way of sorting the keyword-value pairs, and sorting doesn't change their correspondence.
Array ([DE] => Germany
[In] => India
[ES] => Spain
[US] => United States
)
Now, you can certainly guess that this sort can also be inverted, and it uses the Arsort () function to complete this function. Listing F is an example:
Listing F
<?php $data = Array ("US" => "United States", "in" => "India", "DE" => "Germany", "ES" => "Spain"); Arsort ($d ATA); Print_r ($data);
?>
Below is its output, which is inverted alphabetically according to the value. It is easy to see the difference between the following results compared to those produced after the Krsort () function is inverted.
Array ([US] => United States
[ES] => Spain
[In] => India
[DE] => Germany
)
Natural language Sorting
PHP has a very unique sort of way of using cognition rather than using calculation rules. This feature is called Natural language sorting, which is useful when creating fuzzy logic applications. Let's take a look at a simple example of it, as shown in Listing G:
Listing G
<?php $data = Array ("Book-1", "book-10", "book-100", "book-5"); Sort ($data);p rint_r ($data);
Natsort ($data); Print_r ($data);? >
Its output results are as follows:
Array ([0] => book-1
[1] => book-10
[2] => book-100
[3] => book-5
)
Array
(
[0] => book-1
[3] => book-5
[1] => book-10
[2] => book-100
)
Their differences are clear: the second sort result is more intuitive, more "humane", but the first is more consistent with the algorithm rules, more "computer" characteristics.
is natural language capable of inverted rows? The answer is YES! As long as the Array_reverse () function is used for the results of the Natsort (), Listing H is a simple example:
Listing H
<?php $data = Array ("Book-1", "book-10", "book-100", "book-5"); Natsort ($data); Print_r (Array_reverse ($data));
?>
The following is the output of this result:
Array ([0] => book-100
[1] => book-10
[2] => book-5
[3] => book-1
)
Sort by user-defined rules
PHP also allows you to define your own sorting algorithm, and you can create your own comparison function and pass it to the Usort () function. If the first argument is smaller than the second argument, the comparison function must return a number smaller than 0, and the comparison function should return a number greater than 0 if the first argument is larger than the second argument.
Listing I is an example of this example, in which the shortest items are sorted according to their length, which is at the top of the list:
Listing I
<?php $data = Array ("joe@", "@", "asmithsonian@", "jay@"); Usort ($data, ' Sortbylen ');
Print_r ($data); function Sortbylen ($a, $b) {
if (strlen ($a) = = strlen ($b)) {
return 0;
} else {
Return (strlen ($a) > strlen ($b))? 1:-1;
}
}
?>
This creates our own comparison function, which uses the strlen () function to compare the number of each string and then return 1,0 or-1 respectively. This return value is the basis for determining the arrangement of elements. The following is the output of this result:
Array ([0] => jay@
[1] => joe@
[2] => @
[3] => asmithsonian@
)
Natural language Sorting
PHP has a very unique sort of way of using cognition rather than using calculation rules. This feature is called Natural language sorting, which is useful when creating fuzzy logic applications. Let's take a look at a simple example of it, as shown in Listing G:
Listing G
<?php $data = Array ("Book-1", "book-10", "book-100", "book-5"); Sort ($data);p rint_r ($data);
Natsort ($data); Print_r ($data);? >
Its output results are as follows:
Array ([0] => book-1
[1] => book-10
[2] => book-100
[3] => book-5
)
Array
(
[0] => book-1
[3] => book-5
[1] => book-10
[2] => book-100
)
Their differences are clear: the second sort result is more intuitive, more "humane", but the first is more consistent with the algorithm rules, more "computer" characteristics.
is natural language capable of inverted rows? The answer is YES! As long as the Array_reverse () function is used for the results of the Natsort (), Listing H is a simple example:
Listing H
<?php $data = Array ("Book-1", "book-10", "book-100", "book-5"); Natsort ($data); Print_r (Array_reverse ($data));
?>
The following is the output of this result:
Array ([0] => book-100
[1] => book-10
[2] => book-5
[3] => book-1
)
Sort by user-defined rules
PHP also allows you to define your own sorting algorithm, and you can create your own comparison function and pass it to the Usort () function. If the first argument is smaller than the second argument, the comparison function must return a number smaller than 0, and the comparison function should return a number greater than 0 if the first argument is larger than the second argument.
Listing I is an example of this example, in which the shortest items are sorted according to their length, which is at the top of the list:
Listing I
<?php $data = Array ("joe@", "@", "asmithsonian@", "jay@"); Usort ($data, ' Sortbylen ');
Print_r ($data); function Sortbylen ($a, $b) {
if (strlen ($a) = = strlen ($b)) {
return 0;
} else {
Return (strlen ($a) > strlen ($b))? 1:-1;
}
}
?>
This creates our own comparison function, which uses the strlen () function to compare the number of each string and then return 1,0 or-1 respectively. This return value is the basis for determining the arrangement of elements. The following is the output of this result:
Array ([0] => jay@
[1] => joe@
[2] => @
[3] => asmithsonian@
)
Multidimensional sorting
Finally, PHP allows you to perform some more complex sorting on a multidimensional array--for example, first by using a normal keyword for a nested group, and then sorting according to another keyword. This is very similar to sorting multiple fields with an order BY statement that uses SQL. To better understand how it works, take a closer look at listing J's example:
Listing J
<?php $data = Array (array ("id" => 1, "name" => "Boney M", "rating" => 3),
Array ("id" => 2, "name" => "Take that", "rating" => 1),
Array ("ID" => 3, "name" => "The Killers", "rating" => 4),
Array ("ID" => 4, "name" => "Lusain", "rating" => 3),
); foreach ($data as $key => $value) {
$name [$key] = $value [' name '];
$rating [$key] = $value [' rating '];
}
Array_multisort ($rating, $name, $data); Print_r ($data);? >
Here, we simulate a row and column array in the $DATA array. Then, I use the Array_multisort () function to rearrange the data collection, first by sorting by rating, and then, if rating is equal, sorted by name. Its output results are as follows:
Array ([0] => Array
(
[ID] => 2
[Name] => Take that
[Rating] => 1
) [1] => Array
(
[ID] => 1
[Name] => Boney M
[Rating] => 3
)
[2] => Array
(
[ID] => 4
[Name] => Lusain
[Rating] => 3
)
[3] => Array
(
[ID] => 3
[Name] => The Killers
[Rating] => 4
)
)
The Array_multisort () function is one of the most useful functions in PHP, and it has a very wide range of applications. In addition, as you can see in the example, it is able to sort multiple unrelated arrays, or you can use one of these elements as the basis for the next order, and you can sort the database result sets.
These examples should give you a rudimentary understanding of the use of various array sorting functions in PHP, and also show you some of the internal functionality hidden in the PHP array processing toolkit.

The above is the PHP specified field of multidimensional array sorting method, I hope this section of PHP code to help you

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.