我需要php中的一个函数来根据任意顺序对单词列表进行排序。
列表中任何不符合我预定义顺序的单词都应该按字母顺序排列在列表末尾。
下面是我的第一次尝试,它既不优雅也不高效。你能提出一个更好的方法来实现这一点吗?
感谢
public static function sortWords(&$inputArray){
$order=array("Banana","Orange", "Apple", "Kiwi");
sort($inputArray);
for($i=0;$i<count($inputArray));$i++){
$ac = $inputArray[$i];
$position = array_search($ac,$order);
if($position !== false && $i != $position){
$temp=$inputArray[$position];
$inputArray[$position]=$inputArray[$i];
$inputArray[$i]=$temp;
}
}
}
PHP提供了usort()
和uksort()
函数,允许您编写自己的排序例程。在这两个中,你会想要usort()
。
这两个函数都希望您编写一个独立的函数,该函数将输入数组的两个元素作为输入,并返回它们应该排序的顺序。usort()
函数然后运行自己的排序算法,根据需要经常调用函数as来建立排序顺序,直到它对整个数组进行排序为止。
所以你会写这样的东西。。。。
function mycompare($a, $b) {
if ($a == $b) {return 0;}
$order=array("Banana","Orange", "Apple", "Kiwi");
$position = array_search($a,$order);
$position2 = array_search($b, $order);
//if both are in the $order, then sort according to their order in $order...
if ($position2!==false && $position!==false) {return ($position < $position2) ? -1 : 1;}
//if only one is in $order, then sort to put the one in $order first...
if($position!==false) {return -1;}
if($position2!==false) {return 1;}
//if neither in $order, then a simple alphabetic sort...
return ($a < $b) ? -1 : 1;
}
然后调用CCD_ 5对它们进行排序。
public static function sortWords($inputArray){
$order=array("Banana","Orange", "Apple", "Kiwi");
$sorted_array = array_diff($inputArray,$order);
sort($sorted_array);
$rest_array = array_intersect($order,$inputArray);
$result = array_merge($rest_array,$sorted_array);
return $result;
}
还没有测试,但试试这个。
可能比Headshota的解决方案慢,但只是为您提供另一种(未测试(可能性:
function sortWordsCmp($a, $b) {
$order=array("Banana","Orange", "Apple", "Kiwi");
$a = array_search($a, $order);
$b = array_search($b, $order);
if ($a === $b)
return 0;
return (($b===false) || ($a < $b)) ? -1 : +1;
}
public static function sortWords($inputArray){
usort($inputArray, 'sortWordsCmp');
return $inputArray;
}
public static function sortByArbitraryKeys(&$inputArray, $sort_order) {
$sort_order = array_flip($sort_order);
uksort($inputArray, function ($a, $b) use ($sort_order) {
return $sort_order[$a] - $sort_order[$b];
}
}
举个例子如下。。。
// Doe, John L.
$this->full_name = ['last_name'=>'Doe', 'first_name'=>'John', 'middle_initial'=>'L.'];
// John L. Doe
$this->sortByArbitraryKeys($this->full_name, ['first_name', 'middle_initial', 'last_name']);
无论您的具体用例是什么,您都可以轻松地重构它。