use*_*166 7 php sorting string
我想在PHP中对字符串进行排序,匹配应该首先在子字符串的第一个字母上完成,然后在整个字符串的字母上完成.
例如,如果有人搜索do,则列表包含
Adolf
Doe
Done
Run Code Online (Sandbox Code Playgroud)
结果应该是
Doe
Done
Adolf
Run Code Online (Sandbox Code Playgroud)
使用常规sort($array, SORT_STRING)或不起作用的东西,阿道夫先于其他人排序.
有人知道怎么做吗?
您可以根据以下顺序对字符串进行排序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
Run Code Online (Sandbox Code Playgroud)