php按字母顺序按字符串中的最后一个字排序数组

时间:2013-04-28 22:51:39

标签: php arrays

我有一个数组。例如:

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

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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");

答案 2 :(得分: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 :(得分: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);

 ?>