我想在 PHP 中对字符串进行排序,首先应该在子字符串的第一个字母上进行匹配,然后在整个字符串的字母上进行匹配。
例如,如果有人搜索do
,并且列表包含
Adolf
Doe
Done
结果应该是
Doe
Done
Adolf
使用常规sort($array, SORT_STRING)
或类似的东西不起作用,阿道夫在其他人之前排序。
有人知道怎么做吗?
我会使用自定义排序:
<?php
$list = ['Adolf', 'Doe', 'Done'];
function searchFunc($needle)
{
return function ($a, $b) use ($needle)
{
$a_pos = stripos($a, $needle);
$b_pos = stripos($b, $needle);
# if needle is found in only one of the two strings, sort by that one
if ($a_pos === false && $b_pos !== false) return 1;
if ($a_pos !== false && $b_pos === false) return -1;
# if the positions differ, sort by the first one
$diff = $a_pos - $b_pos;
# alternatively: $diff = ($b_pos === 0) - ($a_pos === 0)
if ($diff) return $diff;
# else sort by natural case
return strcasecmp($a, $b);
};
}
usort($list, searchFunc('do'));
var_dump($list);
输出:
array(3) {
[0] =>
string(3) "Doe"
[1] =>
string(4) "Done"
[2] =>
string(5) "Adolf"
}
usort(array, callback)
让您根据回调进行排序。
示例(类似这样的,没试过)
usort($list, function($a, $b) {
$posa = strpos(tolower($a), 'do');
$posb = strpos(tolower($b), 'do');
if($posa != 0 && $posb != 0)return strcmp($a, $b);
if($posa == 0 && $posb == 0)return strcmp($a, $b);
if($posa == 0 && $posb != 0)return -1;
if($posa != 0 && $posb == 0)return 1;
});
您可以根据顺序对字符串进行排序,stripos($str, $search)
以便前面 ( stripos() == 0
) 中的字符串首先出现。
以下代码将搜索字符串的子字符串位置推送到单独的数组中,然后用于array_multisort()
对匹配项应用正确的排序;这样做而不是usort()
避免stripos()
多次调用。
$k = array_map(function($v) use ($search) {
return stripos($v, $search);
}, $matches);
// $k contains all the substring positions of the search string for all matches
array_multisort($k, SORT_NUMERIC, $matches, SORT_STRING);
// $matches is now sorted against the position