2013-04-28 46 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

相關問題