This should do it:
usort($users, 'wpse_235438_sort_users' );
function wpse_235438_sort_users( $a, $b ) {
$a_last_name = array_pop( explode( ' ', $a->last_name ) );
$b_last_name = array_pop( explode( ' ', $b->last_name ) );
return strnatcasecmp( $a_last_name, $b_last_name );
}
explode()
will convert your names into arrays; array_pop()
will give you the last item in those arrays, which is what you’re looking for. Then you just do the comparison you were already doing to sort them.
Using an anonymous function
Per the PHP page on create_function()
, if you’re using PHP 5.3 or newer, you should use an anonymous function (or “closure”) instead of create_function()
.
usort($users, function( $a, $b ) {
$a_last_name = array_pop( explode( ' ', $a->last_name ) );
$b_last_name = array_pop( explode( ' ', $b->last_name ) );
return strnatcasecmp( $a_last_name, $b_last_name );
} );