1

I'm using the code below to sort a list of users by their first name, but I need help with the sortByName function because I'd like to sort the list by last name as a secondary. so if there are two Bob's, instead of ordering them randomly, it will order them alphabetically by last name. I tried adding an if statement for when the first names are identical, but I just ended up breaking it somehow...

function sortByName($a, $b) {
    // if($a['first'] == $b['first']) // commented out because it doesn't work
    //     return $a['last'] > $b['last'];
    // else
           return $a['first'] > $b['first']; // this works on its own
}

$a = array( // of usernames // );
$userList = array();

foreach($a as $b) {
    $id = $users->fetch_info('id', 'username', $b); // get users' id from their username
    $userList[] = $users->userdata($id); // get users' information (like first and last name)
}

usort($userList, 'sortByName');

foreach($userList as $profile) {
    $u = $profile['username'];
    $first = $profile['first'];
    $last = $profile['last'];

    include 'user-list.php';
}

1 Answer 1

1

Check if the first names are similar, then fall back to last name.

function sortByName($a, $b) {
    if ($a["first"] === $b["first"]) { // 2 Bobs!
        return strcmp($a["last"], $b["last"]);
    }
    return strcmp($a["first"], $b["first"]);
}

I used strcmp, use strcasecmp for case-insensitive sorting and strnatcmp for natural order sort.

Natural order sort deals mostly with numbers: "a200" should come after "a3".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.