php根据字符串对数组进行排序
问题描述:
我有一个像这样的数组:
I have an array like this:
['ball', 'football', 'volleyball', 'football player', 'football league', 'tennis']
我想根据足球"关键字对它进行如下排序:
I want to sort it like the following based on "football" keyword:
['football', 'football player', 'football league', 'ball', 'volleyball', 'tennis']
我该如何实现?
答
您需要创建一个自定义排序函数,然后将其与usort.
You need to make a custom sort function, and then use it with usort.
$array=["ball","football","volleyball","football player","football league","tennis"];
function footsort($a,$b) {
$afoot=substr($a,0,8)=="football";
$bfoot=substr($b,0,8)=="football";
if ($afoot==$bfoot) return strcmp($a,$b);
/*else*/
if ($afoot) return -1;
if ($bfoot) return 1;
}
usort($array,"footsort");
print_r($array);
响应:
Array
(
[0] => football
[1] => football league
[2] => football player
[3] => ball
[4] => tennis
[5] => volleyball
)