2

I have an array i need sorted alphabetically, by first name.

how can i name each array element with the firstname so I can use the sort function.

function...

<?php
// fetches all for the users from the table
function fetch_users_directory(){
$result = mysql_query('SELECT `user_lastname` AS `lastname`, 
                              `user_firstname` AS `firstname`, 
                              `user_id` AS `id` FROM `users`');
$users = array();
while(($row = mysql_fetch_assoc($result)) !== false){
    $test = mysql_query('SELECT `user_firstname` FROM `users`');
    $users[] = $row;
}
return $users;
print_r($user);
?>

result is...

Array
(
[3] => Array
    (
        [lastname] => Stoss
        [firstname] => Alex
        [id] => 1
    )

[4] => Array
    (
        [lastname] => Kennedy
        [firstname] => Alice 
        [id] => 2
    )

[5] => Array
    (
        [lastname] => Williams
        [firstname] => Anna
        [id] => 3
    )

[6] => Array
    (
        [lastname] => De Jong
        [firstname] => Anna
        [id] => 4
    )

[7] => Array
    (
        [lastname] => Goodwin
        [firstname] => Ash
        [id] => 5
    )

how can this be ordered alphabetically by firstname then lastname?

jcsanyi
  • 8,133
  • 2
  • 29
  • 52
charlie
  • 23
  • 3
  • Welcome to StackOverflow. **[Please, don't use the mysql_* functions for new code.](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)** They are no longer maintained and are officially deprecated. See the **[red box](http://php.net/manual/en/function.mysql-connect.php)**? You can use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) instead - [this page](http://php.net/manual/en/mysqlinfo.api.choosing.php) can help you decide which to use. – jcsanyi Jul 19 '13 at 05:11
  • Why not order them in the query by using `ORDER_BY firstname, lastname`? – omma2289 Jul 19 '13 at 05:13
  • Why the extra (unused) query `$test = mysql_query(...` inside your loop? – jcsanyi Jul 19 '13 at 05:15
  • Thanks @jcsanyi i didn't realise mysql_* was outdated im only just getting into mysql and php. The link provided, Please, don't use the mysql_* functions for new code, was really helpful also. – charlie Jul 19 '13 at 05:43

1 Answers1

2

The easiest way to sort these results is to do it as part of your query:

SELECT `user_lastname` AS `lastname`,
       `user_firstname` AS `firstname`,
       `user_id` AS `id`
FROM `users`
ORDER BY `firstname` ASC, `lastname` ASC

If you want to sort it in PHP though, the best way is to use usort() with strcmp():

usort($users, function($a, $b) {
    if ($a['firstname'] != $b['firstname']) {
        return strcmp($a['firstname'], $b['firstname']);
    } else {
        return strcmp($a['lastname'], $b['lastname']);
    }
});

usort() will call the callback function in order to compare two items - and your callback needs to return a value of <0, 0, or >0 to indicate the first item comes before, is the same as, or comes after the second item.

strcmp() already compares two strings and returns a value like this - so we can leave the actual comparison to strcmp(), and have the usort() callback function just handle the logic of picking the right strings to compare, and falling back to lastname in the event the firstname values are equal.

It might help to understand this even more to realize that running the standard PHP sort() function on an array of strings is pretty much the same as running usort($array, 'strcmp');


An alternate solution which you seem to be hinting at in your question would be to use the string you want to sort on as the key of the $users array, and then use ksort() to sort it.

In this case, the string you're sorting on would be "firstname lastname", so you could put that into your loop like this:

while(($row = mysql_fetch_assoc($result)) !== false){
    $users[$row['firstname'] . ' ' . $row['lastname']] = $row;
}
ksort($users);
jcsanyi
  • 8,133
  • 2
  • 29
  • 52
  • ok so it will sort the first name ok. but why is is ignoring the last names? ORDER BY `firstname` ASC, `lastname` ASC? – charlie Jul 19 '13 at 05:58
  • As long as the first names are different, it'll sort entirely by first name, and ignore the last name. It'll just use the last name to sort two values that have the same first name. In your example, that's just Anna Williams and Anna De Jong - who will be sorted with Ann De Jong first. – jcsanyi Jul 19 '13 at 06:21
  • Were you actually trying to sort primarily by last name, not first? – jcsanyi Jul 19 '13 at 06:21
  • yea thats what i thought.. but at the moment its ignoring the last name? all first name values are ordered but ignoring the last names, ie "John Doe" is ordered before "John Adams"? – charlie Jul 19 '13 at 11:57
  • on a side note... other than youtube and and codeacademy.com does anyone recommend any external based schools/courses to learn all this stuff? stuff being the big picture.. – charlie Jul 19 '13 at 12:02
  • ie...{ [0] => Array ( [firstname] => Alex [lastname] => Stoss [id] => 1 ) [1] => Array ( [firstname] => Alice [lastname] => Kennedy [id] => 2 ) [2] => Array ( [firstname] => Anna [lastname] => De Jong [id] => 4 ) – charlie Jul 19 '13 at 12:08