微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php基于字符串排序数组

我有这样一个数组:

['ball', 'football', 'volleyball', 'football player', 'football league', 'tennis']

我想基于“football”关键字将其排序为以下内容

['football', 'football player', 'football league', 'ball', 'volleyball', 'tennis']

我怎样才能做到这一点?

解决方法:

您需要创建自定义排序功能,然后将其与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
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐