Nav*_*eed 10 php sorting algorithm performance
我想在PHP中按字母顺序对数组的值进行排序.如果所有值都以相同的字符开头,那么它们应该使用第二个字符进行排序,依此类推.忽略区分大小写.
例如:
before:
values[0] = "programming";
values[1] = "Stackoverflow";
values[2] = "question";
values[3] = "answers";
values[4] = "AA Systems";
after:
values[0] = "AA Systems";
values[1] = "answers";
values[2] = "programming";
values[3] = "question";
values[4] = "Stackoverflow";
Run Code Online (Sandbox Code Playgroud)
我找到了一些算法,但我想要一种快速且语句数量少的方法.忽略区分大小写对我来说很特别.谢谢.
ken*_*ytm 14
看到
natcasesort:http://www.php.net/manual/en/function.natcasesort.phpusort:http://www.php.net/manual/en/function.usort.php,带有比较strtolower(a)和比较的比较器功能strtolower(b).您的示例有两个假设:
你只处理简单的一维数组.
按字母顺序排序后,您的索引将更新,以便按字母顺序将第一个元素分配给键0,依此类推.
给定这些参数,最简单的解决方案是使用数组方法sort().用你的例子:
$values[0] = "programming";
$values[1] = "Stackoverflow";
$values[2] = "question";
$values[3] = "answers";
$values[4] = "AA Systems";
sort($values);
Run Code Online (Sandbox Code Playgroud)
这将导致以下结果:
Array {
[0] => AA Systems
[1] => Stackoverflow
[2] => answers
[3] => programming
[4] => question
}
Run Code Online (Sandbox Code Playgroud)
There are other array sorting functions that might be a better fit. For instance, the simple one I use above puts upper-case in front of lower-case, so if you had "security" as an item (all lower-case) it would go after "Stackoverflow" since the upper-case s would take precedence over se vs. st. To sort without case-sensitivity, you could use natcasesort(), which would produce the following with the given array:
Array {
[0] => AA Systems
[1] => answers
[2] => programming
[3] => question
[4] => Stackoverflow
}
Run Code Online (Sandbox Code Playgroud)