PHP-implemented custom array sorting function and sorting class example

Source: Internet
Author: User
PHP-based custom array sorting function and sorting class example this article describes the PHP-based custom array sorting function and sorting class. We will share this with you for your reference. The details are as follows:

/** Two-dimensional array custom sorting function * uasort ($ arr, function_name) ***/$ arr = array ('a' => 1, 'B' => 'C'), array ('a' => 4, 'B' => 'A'), array ('a' => 5, 'B' => 'g'), array ('a' => 7, 'B' => 'F'), array ('a' => 6, 'B' => 'e'); function compare_arr ($ x, $ y) {if ($ x ['B'] <$ y ['B']) {return-1;} else if ($ x ['B']> $ y ['B']) {return 1 ;}else {return 0 ;}} uasort ($ arr, 'Compare _ arr'); foreach ($ arr as $ a) {echo $ a ['A']. '=> '. $ a ['B'].'
';}

Custom sorting class in the manual:

Class multiSort {var $ key; // key in your array // The sorting function parameters are sorted by the array index in sequence. function run ($ myarray, $ key_to_sort, $ type_of_sort = '') {$ this-> key = $ key_to_sort; if ($ type_of_sort = 'desc') uasort ($ myarray, array ($ this, 'myreverse _ compare'); else uasort ($ myarray, array ($ this, 'mycompare'); return $ myarray;} // positive sequence function mycompare ($ x, $ y) {if ($ x [$ this-> key] =$ y [$ this-> key]) return 0; else if ($ x [$ this-> key] <$ y [$ this-> key]) return-1; else return 1 ;} // reverse function myreverse_compare ($ x, $ y) {if ($ x [$ this-> key] = $ y [$ this-> key]) return 0; else if ($ x [$ this-> key]> $ y [$ this-> key]) return-1; else return 1 ;}}

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.