I tried some of the methods from this post: Sort array by object property in PHP?
But I am not able to sort by the last name of my person array in wordpress.
Here is what I do:
<?php
function personSort( $a, $b ) {
return $a->last_name == $b->last_name ? 0 : ( $a->last_name > $b->last_name ) ? 1 : -1;
}
usort( $autlist, 'personSort' );
foreach($autlist as $al){ ?>
<option value="<?php echo $al->ID; ?>"><?php echo $al->first_name.' '.$al->last_name; ?></option>
The order comes out like this:
Nick Hammond
Peter Ruck
Nam Ol Lamon
What am I doing wrong?
You cannot compare strings using the <
and >
comparison operators, they are reserved for numbers in PHP. If you do, your strings are transparently type-casted to numbers first, probably all evaluating to 0
, hence the seemingly random result.
Try using strcmp(), which compares strings and returns a number, just like what usort()
expects:
function personSort( $a, $b ) {
return strcmp($a->last_name, $b->last_name);
}
Note that starting with PHP 5.3, you can avoid declaring a function in the global scope, and use an anonymous function instead:
usort($autlist, function ($a, $b) {
return strcmp($a->last_name, $b->last_name);
});