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;
}
…然后只需调用usort($inputarray,’mycompare’);对它们进行排序