[英]Sorting an array with uksort()
I have an array like this one: 我有一个像这样的数组:
$a = array("MA1" => 0, "MA10" => 1, "MA20" => 2, "MA5" => 3, "SM10" => 4, "SM8" => 5, "SM20" => 6, "SN33" => 7);
I want to sort it, that I will have the following order: 我要对其进行排序,这样我将具有以下顺序:
$a = array("MA1" => 0, "MA5" => 3, "MA10" => 1, "MA20" => 2, "SM8" => 5, "SM10" => 4, "SM20" => 6, "SN33" => 7);
So I need a order which is alphabetical within the first two chars and numeric of the rest. 因此,我需要一个在前两个字符内按字母顺序排列且其余部分按数字排列的顺序。 So I think I have to do this with
所以我认为我必须这样做
uksort($a, "cmp");
So I need a function like this: 所以我需要这样的功能:
function cmp($a, $b) {
// ???
return strcasecmp($a, $b);
}
How do I need to write the function so that the order will be right? 我该如何编写函数以便顺序正确?
Thank you in advance & Best Regards. 预先感谢您和最诚挚的问候。
You can use built-in natural comparison function: 您可以使用内置的自然比较功能:
$a = array("MA1" => 0, "MA10" => 1, "MA20" => 2, "MA5" => 3, "SM10" => 4, "SM8" => 5, "SM20" => 6, "SN33" => 7);
uksort($a, "strnatcasecmp");
print_r($a);
The code above would produce following output: 上面的代码将产生以下输出:
Array
(
[MA1] => 0
[MA5] => 3
[MA10] => 1
[MA20] => 2
[SM8] => 5
[SM10] => 4
[SM20] => 6
[SN33] => 7
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.