我有和数组看起来像这样
Array
(
[0] => Array
(
[key] => 0
[val] => 0
)
[1] => Array
(
[key] => 11
[val] => 1:1
)
[2] => Array
(
[key] => 1100
[val] => 1:100
)
[3] => Array
(
[key] => 112
[val] => 1:12
)
[4] => Array
(
[key] => 1144
[val] => 1:144
)
[5] => Array
(
[key] => 1146
[val] => 1:146
)
[6] => Array
(
[key] => 116
[val] => 1:16
)
[7] => Array
(
[key] => 118
[val] => 1:18
)
[8] => Array
(
[key] => 120
[val] => 1:20
我想通过数组中的KEY键对其进行排序
我使用以下代码
usort($arrScale,"cmd");
function cmp($a, $b)
{
if ($a["key"] == $b["key"]) {
return 0;
}
return ($a["key"] < $b["key"]) ? -1 : 1;
}
1100和1144应该更接近尾声?我做错了吗?
答案 0 :(得分:4)
键值是字符串,按字符串比较规则“1144”比“116”小“。将它们转换为int以进行比较。
function cmp($a, $b)
{
$aKey = (int) $a["key"];
$bKey = (int) $b["key"];
if ($aKey == $bKey) {
return 0;
}
return ($aKey < $bKey) ? -1 : 1;
}