List Users alphabetically with heading

After a good bit of tinkering I’ve come up with something. It’s certainly not the BEST method, but since there’s not a good way to do it through the core directly without having to do a bunch of array-reordering, I think SQL is a better solution here. Anyways, the SQL is as follows:

SELECT users.*, meta.meta_value
FROM $wpdb->users AS users LEFT JOIN $wpdb->usermeta AS meta
    ON users.ID = meta.user_id
WHERE meta.meta_key = 'first_name'
    AND meta.meta_value != ''
ORDER BY meta.meta_value ASC

Nothing special going on there, it just gets all the values from the users table where there’s a first name set.

For the list you can just iterate through those results, it’s pretty simple to do that. The only thing that you will need to do is get the headings to work right. If you store the heading, then do a case-insensitive compare, this should be pretty easy. For example (pseudocode):

$cur_first_letter = substr( $first_name, 0, 1 );

if( strtoupper( $cur_first_letter ) != strtoupper( $prev_first_letter ) ) {
    // output header for strtoupper( $cur_first_letter )
}

$prev_first_letter = $cur_first_letter;

Note: The SQL is tested, the PHP is not (obviously, since it’s pseudocode).