# Posted By

beneberle on 06/02/11

# Statistics

Viewed 687 times
Favorited by 0 user(s)

# Multi-Dimensional Array/Object Sort using usort and custom comparison function

/ Published in: PHP
`<?php /** *  * EXAMPLE #1 * * sort array of objects based on specified attribute values * in this case "lastname", followed by "firstname" *  **/ \$person1 = (object) array('lastname' => 'Jones', 'firstname' => 'Michael', 'Degree' => 'AAA');\$person2 = (object) array('lastname' => 'Adams', 'firstname' => 'Zach', 'Degree' => 'BB');\$person3 = (object) array('lastname' => 'Smith', 'firstname' => 'Jim', 'Degree' => 'CCC');\$person4 = (object) array('lastname' => 'Adams', 'firstname' => 'Tom', 'Degree' => 'DD'); \$array_to_be_sorted = array( \$person1, \$person2, \$person3, \$person4); echo "Before";echo "<pre>";print_r(\$array_to_be_sorted);echo "</pre>";echo "<br /><br />"; function alpha_sort(\$a, \$b) {     if (\$a->lastname == \$b->lastname) {        return strnatcmp(\$a->firstname, \$b->firstname);    }    return strnatcmp(\$a->lastname, \$b->lastname);} usort(\$array_to_be_sorted, "alpha_sort"); echo "After";echo "<pre>";print_r(\$array_to_be_sorted);echo "</pre>"; ?> <?php /** *  * EXAMPLE #2 * * sort array of arrays based on specified array keys * in this case "lastname", followed by "firstname" *  **/  \$array_to_be_sorted = array(    array('lastname' => 'Jones', 'firstname' => 'Michael'),    array('lastname' => 'Adams', 'firstname' => 'Zach'),    array('lastname' => 'Smith', 'firstname' => 'Jim'),    array('lastname' => 'Adams', 'firstname' => 'Tom')); function alpha_sort(\$a, \$b) {     if (\$a['lastname'] == \$b['lastname']) {        return strnatcmp(\$a['firstname'], \$b['firstname']);    }    return strnatcmp(\$a['lastname'], \$b['lastname']);} usort(\$array_to_be_sorted, "alpha_sort"); echo "<pre>";print_r(\$array_to_be_sorted);echo "</pre>"; ?>`