PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 4.18 Sorting an Array by a Computable Field

4.18.1 Problem

You want to define your own sorting routine.

4.18.2 Solution

Use usort( ) in combination with a custom comparison function:

// sort in reverse natural order
function natrsort($a, $b) {
    return strnatcmp($b, $a);
}

$tests = array('test1.php', 'test10.php', 'test11.php', 'test2.php');
usort($tests, 'natrsort');

4.18.3 Discussion

The comparison function must return a value greater that 0 if $a > $b, 0 if $a == $b, and a value less than 0 if $a < $b. To sort in reverse, do the opposite. The function in the Solution, strnatcmp( ), obeys those rules.

To reverse the sort, instead of multiplying the return value of strnatcmp($a, $b) by -1, switch the order of the arguments to strnatcmp($b, $a).

The sort function doesn't need to be a wrapper for an existing sort. For instance, the pc_date_sort( ) function, shown in Example 4-2, shows how to sort dates.

Example 4-2. pc_date_sort( )
// expects dates in the form of "MM/DD/YYYY"
function pc_date_sort($a, $b) {
    list($a_month, $a_day, $a_year) = explode('/', $a);
    list($b_month, $b_day, $b_year) = explode('/', $b);

    if ($a_year  > $b_year ) return  1;
    if ($a_year  < $b_year ) return -1;

    if ($a_month > $b_month) return  1;
    if ($a_month < $b_month) return -1;

    if ($a_day   > $b_day  ) return  1;
    if ($a_day   < $b_day  ) return -1;

    return 0;
}

$dates = array('12/14/2000', '08/10/2001', '08/07/1999');
usort($dates, 'pc_date_sort');

While sorting, usort( ) frequently recomputes the sort function's return values each time it's needed to compare two elements, which slows the sort. To avoid unnecessary work, you can cache the comparison values, as shown in pc_array_sort( ) in Example 4-3.

Example 4-3. pc_array_sort( )
function pc_array_sort($array, $map_func, $sort_func = '') {
    $mapped = array_map($map_func, $array);    // cache $map_func( ) values

    if ('' == $sort_func) { 
        asort($mapped);                        // asort( ) is faster then usort( )
    }  else { 
        uasort($mapped, $sort_func);           // need to preserve keys
    }

    while (list($key) = each($mapped)) {
        $sorted[ ] = $array[$key];              // use sorted keys
    }

    return $sorted;
}

To avoid unnecessary work, pc_array_sort( ) uses a temporary array, $mapped, to cache the return values. It then sorts $mapped, using either the default sort order or a user-specified sorting routine. Importantly, it uses a sort that preserves the key/value relationship. By default, it uses asort( ) because asort( ) is faster than uasort( ). (Slowness in uasort( ) is the whole reason for pc_array_sort( ) after all.) Finally, it creates a sorted array, $sorted, using the sorted keys in $mapped to index the values in the original array.

For small arrays or simple sort functions, usort( ) is faster, but as the number of computations grows, pc_array_sort( ) surpasses usort( ). The following example sorts elements by their string lengths — a relatively quick custom sort:

function pc_u_length($a, $b) {
    $a = strlen($a);
    $b = strlen($b);

    if ($a == $b) return  0;
    if ($a  > $b) return  1;
                  return -1;
}

function pc_map_length($a) {
    return strlen($a);
}

$tests = array('one', 'two', 'three', 'four', 'five',
               'six', 'seven', 'eight', 'nine', 'ten');

// faster for < 5 elements using pc_u_length()
usort($tests, 'pc_u_length');

// faster for >= 5 elements using pc_map_length()
$tests = pc_array_sort($tests, 'pc_map_length');

Here, pc_array_sort( ) is faster than usort( ) once the array reaches five elements.

4.18.4 See Also

Recipe 4.17 for basic sorting and Recipe 4.19 for sorting multiple arrays; documentation on usort( ) at http://www.php.net/usort, asort( ) at http://www.php.net/asort, and array_map( ) at http://www.php.net/array-map.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    Chapter 4. Arrays
    4.1 Introduction
    Recipe 4.2 Specifying an Array Not Beginning at Element 0
    Recipe 4.3 Storing Multiple Elements per Key in an Array
    Recipe 4.4 Initializing an Array to a Range of Integers
    Recipe 4.5 Iterating Through an Array
    Recipe 4.6 Deleting Elements from an Array
    Recipe 4.7 Changing Array Size
    Recipe 4.8 Appending One Array to Another
    Recipe 4.9 Turning an Array into a String
    Recipe 4.10 Printing an Array with Commas
    Recipe 4.11 Checking if a Key Is in an Array
    Recipe 4.12 Checking if an Element Is in an Array
    Recipe 4.13 Finding the Position of an Element in an Array
    Recipe 4.14 Finding Elements That Pass a Certain Test
    Recipe 4.15 Finding the Largest or Smallest Valued Element in an Array
    Recipe 4.16 Reversing an Array
    Recipe 4.17 Sorting an Array
    Recipe 4.18 Sorting an Array by a Computable Field
    Recipe 4.19 Sorting Multiple Arrays
    Recipe 4.20 Sorting an Array Using a Method Instead of a Function
    Recipe 4.21 Randomizing an Array
    Recipe 4.22 Shuffling a Deck of Cards
    Recipe 4.23 Removing Duplicate Elements from an Array
    Recipe 4.24 Finding the Union, Intersection, or Difference of Two Arrays
    Recipe 4.25 Finding All Element Combinations of an Array
    Recipe 4.26 Finding All Permutations of an Array
    Recipe 4.27 Program: Printing an Array in a Horizontally Columned HTML Table
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele