2013-04-28 45 views
3

我有一个数组。例如:php按字母顺序排列字符串中的最后一个字

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

而且我想按字母顺序排列姓氏(字符串中的最后一个字)。这可以做到吗?

+0

是的,你将不得不打破这个数组与fname和lname关联数组,并使用lname排序.. – Dinesh 2013-04-28 22:53:51

+0

可能的重复:http://stackoverflow.com/questions/9370615/how-to-sort-an-array-of-names-by-surname-preserving-the-keys – 2013-04-28 22:57:48

回答

5
$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); 

在线演示:http://ideone.com/jC8Sgx

+0

谢谢...这是非常直截了当的。 – Cybercampbell 2013-04-28 23:27:08

0

你想查看的第一个功能是sort。 接下来,explode

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

您可以使用名为usorthttp://php.net/manual/en/function.usort.php)的自定义排序功能。这使您可以创建您指定的比较功能。

所以,你创建了一个这样的功能...

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)); 
} 

,你使用usort使用此功能进行最终的排序:

usort($your_array, "last_name_compare"); 
+1

这是非常棒的。 – 2013-04-28 23:00:42

0

总会有另一种方法:

<?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); 

?> 
+0

是的,然后你需要将它恢复到原来的状态,有点矫枉过正。 – 2013-04-28 23:05:20

+0

我知道...我知道......但否则数组看起来没有排序。 = P – 2013-04-28 23:10:29

相关问题