php根据字符串对数组进行排序 [英] php sorting an array based on a string
本文介绍了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
)
这篇关于php根据字符串对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文