5

I have an array. eg:

names = {
    'John Doe',
    'Tom Watkins',
    'Jeremy Lee Jone',
    'Chris Adrian'
    }

And I want to order it alphabetically by last name(last word in string). Can this be done?

1
  • yes you will have to break this array to an associative array with fname and lname and than sort using lname.. Commented Apr 28, 2013 at 22:53

4 Answers 4

7
$names = array(
    'John Doe',
    'Tom Watkins',
    'Jeremy Lee Jone',
    'Chris Adrian',
);

usort($names, function($a, $b) {
    $a = substr(strrchr($a, ' '), 1);
    $b = substr(strrchr($b, ' '), 1);
    return strcmp($a, $b);
});

var_dump($names);

Online demo: http://ideone.com/jC8Sgx

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

Comments

4

You can use the custom sorting function called usort (http://php.net/manual/en/function.usort.php). This allows you create a comparison function which you specify.

So, you create a function like so...

function get_last_name($name) {
    return substr($name, strrpos($name, ' ') + 1);
}

function last_name_compare($a, $b) {
    return strcmp(get_last_name($a), get_last_name($b));
}

and you make the ultimate sort using usort using this function:

usort($your_array, "last_name_compare");

Comments

0

The first function you'd like to look at is sort. Next, explode.

$newarray = {};
foreach ($names as $i => $v) {
    $data = explode(' ', $v);
    $datae = count($data);
    $last_word = $data[$datae];
    $newarray[$i] = $last_word; 
}
sort($newarray); 

Comments

0

There comes another approach:

<?php 
// This approach reverses the values of the arrays an then make the sort...
// Also, this: {} doesn't create an array, while [] does =)
$names = [
    'John Doe',
    'Tom Watkins',
    'Jeremy Lee Jone',
    'Chris Adrian'
    ];

foreach ($names as $thisName) {
    $nameSlices = explode(" ", $thisName);
    $sortedNames[] = implode(" ", array_reverse($nameSlices));
}

$names = sort($sortedNames);

print_r($sortedNames);

 ?>

2 Comments

Yes and then you need to reverse it to his original state, a little bit overkill.
I know... I know... But otherwise the arrays doesn't look sorted. =P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.