Chr*_*ris 7 php arrays sorting
我需要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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Spu*_*ley 13
PHP提供了允许您编写自己的排序例程的函数usort()
和uksort()
函数.在这两个中,你会想要的usort()
.
这两个函数都希望您编写一个独立函数,它将输入数组的两个元素作为输入,并返回它们应该排序的顺序.usort()
然后,该函数运行自己的排序算法,调用您的函数,以便根据需要经常建立排序顺序,直到它对整个数组进行排序.
所以你要写这样的东西......
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;
}
Run Code Online (Sandbox Code Playgroud)
...然后打电话usort($inputarray,'mycompare');
给他们排序.
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;
}
Run Code Online (Sandbox Code Playgroud)
还没有测试过,但试试这个。
归档时间: |
|
查看次数: |
2690 次 |
最近记录: |