3.13 Sorting an Array


You want to sort an entire array by your own function because PHP's functions do not fit your need.

Technique

Use the usort() function to specify a user -defined function for sorting the array:

 <?php function cmp_debt($a, $b) {     if ($a[1]== $b[1]) return 0;     return ($b[1] > $a[1]) ? 1 : -1; } // Suppose you have an array that you use to keep track of // how much your buddies owe you after that game of poker. // You want to sort the array from largest debt to lowest, but // regular sorting functions in PHP can't help. $buddy_debts = array(array("John",31),                      array("Dave", 12),                      array("Kris", 15),                      array("Werner", 38),                      array("Phil", 9)); usort($buddy_debts, 'cmp_debt'); foreach ($buddy_debts as $buddy_debt) {     print $buddy_debt[0]." owes ".$buddy_debt[1];     print "<br>"; } ?> 

Comments

The usort() function takes an array and sorts it by a user-defined function; in this case, the function is called cmp_debt() . The function must return -1 , , or 1 . From the PHP manual: "The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. If two members compare as equal, their order in the sorted array is undefined."

We have to resort to using usort() because of the way our $buddy_debts array is structured. PHP's regular sorting functions look only one level deep inside the array, and comparing arrays of arrays is not currently supported.

If you want to use the usort() function without the hassle of declaring an extra sort function, you can use it in conjunction with PHP's create_function() function:

 <?php $buddy_debts = array(array("John",31),                      array("Dave", 12),                      array("Kris", 15),                      array("Werner", 38),                      array("Phil", 9)); usort($buddy_debts,       create_function('$a, $b', 'if ($a[1] == $b[1]) return 0;                        return ($b[1] > $a[1]) ? 1 : -1;'); foreach ($buddy_debts as $buddy_debt) {     print $buddy_debt[0]." owes ".$buddy_debt[1];     print "<br>"; } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net