Sort functions for PHP arrays

Source: Internet
Author: User
Tags locale setting

It is very meaningful to sort the related data stored in the array. There are many functions available in PHP that can be sorted in pairs, which provide a variety of sorting methods. For example, you can pass the value of an element or a key and a custom sort.

① Simple array sorting function
Simple array ordering is the ordering of the values of an array element, and the PHP sort () function and the Rsort () function implement this function. The two functions can be arranged numerically or alphabetically, and have the same parameter list. The function prototypes are as follows:
BOOL Sort (array &array[,int sort_flags])
BOOL Rsort (array &array[,int sort_flags])
The first parameter is required. The latter parameter is optional and gives the sort order, which can be changed by the following values.
Sort_regular: Is the default value that will automatically identify the type of array element to sort.
Sort_numeric: Used for sorting of numeric elements.
Sort_string: Used for the ordering of string elements.
Sort_locale_string: The element is compared as a string based on the current locale setting.

The sort () function sorts the values of the elements in the array in small to large order, and the Rsort () function sorts the values of the elements in the order of large to small. The code used by these two functions is as follows:

123456789 <?php $data = array (5,8,1,7,2);  sort ( $data print_r ( $data //output: Array ([0]=>1 [1]=>2] [2]=>5] [3]=>7 [4]=>8]  rsort ( $data print_r ( $data //output: Array ([0]=>8 [1]=>7] [2]=>5] [3]=>2 [4]=>1] ?>

② sorting arrays by key name
When we use arrays, the Ksort () function and the Krsort () function are often reordered according to the key name. The Ksort function array is sorted by key name from small to large, the Krsort () function and the Ksort () function, in contrast, retain the original key for the array value after sorting.

③ sorting an array based on the value of an element
If you want to sort by using the values of the elements in the array instead of the key-value ordering, PHP will also meet your requirements. You can just use the Asort () function instead of the previously mentioned Ksort () function, and if you sort from large to small, you can use the Arsort () function. The simple sort function, the sort () function, and the Rsort () function are described earlier, and the array is sorted according to the value of the element, and the single primitive key name is ignored, and the subscript of the arrays is re-indexed using numbers. The Asort () function and the Arsort () function retain the original key name and are worth the relationship.

④ sorting an array according to the "natural sort" method
PHP has a very unique sort of method, which uses cognition rather than the use of computational rules, which becomes the "natural sorting Method", where numbers are sorted from 1 to 9, the sorting method of letters from A to Z, and shorter is preferred. This sort of method is useful when creating fuzzy logic applications. You can use Natsort () to sort the array in the "natural sort" method, which ignores the key name when the function is sorted. The function Natcasesort () is a sort of case-insensitive alphabetic array using the "natural sort" algorithm. The code used by these two functions is as follows:

12345678910111213141516171819202122232425262728 <?php$data = array("file1.txt","file11.txt","File2.txt","FILE12.txt","file.txt");natsort($data); //普通的自然排序print_r($data); //输出排序后的结果,数组中包括大小写,输出不是正确的排序结果/*运行结果:Array([3]=>FILE12.txt //大写的元素排在了前面[2]=>File2.txt[4]=>file.txt[0]=>file1.txt[1]=>file11.txt)*/natcasesort($data); //忽略大小写的“自然排序”print_r($data); //输出“自然排序”后的结果,正常结果/*运行结果Array( //使用natcasesort()函数忽略大小写的“自然排序”后的结果[4]=>file.txt [0]=>file1.txt[2]=>File2.txt[1]=>file11.txt[3]=>FILE12.txt)*/?>

⑤ sorting an array based on user-defined rules
PHP provides an array ordering function that can create your own comparison function as a callback function, including functions such as Usort (), Uasort (), and Uksort. They use the same format and have the same argument list, except that the key or value is sorted. The function prototypes are as follows:
BOOL Usort (array &array,callback cmp_function)
BOOL Uasort (array &array,callback cmp_function)
BOOL Ursort (array &array,callback cmp_function)

These three functions will sort the values in an array with a user-defined comparison function. To get a stake in an array that you want to sort on requires a sort of unusual standard, you should use these functions. In a custom callback function, two parameters are required, sequentially passing through two consecutive elements in the array. The comparison function must return an integer less than, equal to, or greater than 0, respectively, when the first argument is considered less than, equal to, or greater than the second argument. In the example below, the shortest items are sorted according to the length of the elements in the array. The code looks like this:

1234567891011121314151617181920 <?php//声明一个数组,其中元素值得长度不相同$lamp = array("Linux","Apache","MySQL","php");//使用usort()函数传入用户自定义的回调函数进行数组排序usort($lamp,"sortByLen");print_r($lamp);//自定义的函数作为回调函数提供给usort()函数使用,声明排序规则function sortByLen($one,$two){//如果两个参数长度相等返回0,在数组中的位置不变if(strlen($one) == strlen($two))return 0;else//第一个参数大于第二个参数返回大于0的数,否则返回小于0的数return (strlen($one)>strlen($two)) ? 1 : -1;}//运行结果 Array([0]=>php [1]=MySQL [2]=>Linux [3]=>Apache)?>

The code in the example above creates its own comparison function, which uses the strlen () function to compare the number of each string, and then returns 1, 0, or-1, which is the basis for determining the arrangement of elements.

⑥ Sorting of multidimensional arrays

PHP also allows you to perform some more complex sorting on multidimensional arrays. For example, first sort a nested array with a common key value, and then sort by another key value. This is similar to sorting multiple fields with an order BY statement that uses SQL. You can use the Array_multisort () function to sort multiple arrays or multidimensional arrays, which sort a multidimensional array based on one dimension or multidimensional.

123456789101112131415161718192021222324252627 <?php//声明一个$data数组,模拟了一个行和列数组$data = array(array("id"=>1,"soft"=>"Linux","rating"=>3),array("id"=>2,"soft"=>"Apache","rating"=>1),array("id"=>3,"soft"=>"MySQL","rating"=>4),array("id"=>4,"soft"=>"PHP","rating"=>2),);//foreach遍历创建两个数组$soft和rating,作为array_multisort的参数foreach($data as $key =>$value){$soft[$key] = $value ["soft"]; //将$data中的每个数组元素中键值为soft的值形成数组$soft$rating[$key] = $value["rating"]; //将每个数组元素中键值为rating的值形成数组$rating}array_multisort($rating,$soft,$data); //使用array_multisort()函数传入三个数组进行排序print_r($data); //输出排序后的二维数组/*运行结果array([0]=>Array([id]=>2 [soft]=>Apache [rating]=>1)[1]=>Array([id]=>4 [soft]=>PHP [rating]=>2)[2]=>Array([id]=>1 [soft]=>Linux [rating]=>3)[3]=>Array([id]=>3 [soft]=>MySQL [rating]=>4))*/?>

The above program simulates a row and column array in the $DATA array. The data collection is then reordered using the Array_multisort () function, first sorted according to the key values in the $rating array, and then, if the element values in the $rating are equal, then sorted according to the $soft array.

The Array_multisort () function is one of the most useful functions in PHP, and it has a very wide range of applications. Also, as you can see in the example, it is possible to sort multiple unrelated arrays, use one of them as the basis for the next sort, and sort the database result set.

>> This article fixed link: http://php.ncong.com/php_course/arry_function/array_paixu.html

>> reprint Please specify: Ntshongwana PHP April 13, 2014 Yuncon PHP Learning tutorial Published

Related Article

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.