如何排序按姓氏$ P $名称的数组pserving键 [英] How to sort an array of names by surname preserving the keys
本文介绍了如何排序按姓氏$ P $名称的数组pserving键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组如下:
Array(
[27] => 'Sarah Green',
[29] => 'Adam Brown',
[68] => 'Fred Able'
);
我想用姓氏和preserve键对它进行排序:
I'd like to sort it by surname and preserve the keys:
Array(
[68] => 'Fred Able'
[29] => 'Adam Brown',
[27] => 'Sarah Green'
);
有些名称可能有两个以上的名字,但它总是我要排序的最后名称。
Some names may have more than two first names, but it's always the very last name I want to sort on.
什么是在PHP中做到这一点的最好方法是什么?
What would be the best way to do this in PHP?
推荐答案
您可以使用 uasort
功能,它允许你指定一个自定义排序方法,同时preserving键:
You can use the uasort
function, which allows you to specify a custom sorting method while also preserving keys:
<?php
// A function to sort by last name.
function lastNameSort($a, $b) {
$aLast = end(explode(' ', $a));
$bLast = end(explode(' ', $b));
return strcasecmp($aLast, $bLast);
}
// The array of data.
$array = array(
27 => 'Sarah Green',
29 => 'Adam Brown',
68 => 'Fred Able'
);
// Perform the sort:
uasort($array, 'lastNameSort');
// Print the result:
print_r($array);
?>
这篇关于如何排序按姓氏$ P $名称的数组pserving键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文