Reputation: 36879
I have and array looks like this
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
I want to sort it by the KEY key in the array
I use the following code
usort($arrScale,"cmd");
function cmp($a, $b)
{
if ($a["key"] == $b["key"]) {
return 0;
}
return ($a["key"] < $b["key"]) ? -1 : 1;
}
1100 and 1144 should be more towards the end?? Am I doing something wrong?
Upvotes: 0
Views: 292
Reputation: 212452
The key values are strings, and by string comparison rules "1144" is 'less' than "116". Cast them to int for your comparisons.
function cmp($a, $b)
{
$aKey = (int) $a["key"];
$bKey = (int) $b["key"];
if ($aKey == $bKey) {
return 0;
}
return ($aKey < $bKey) ? -1 : 1;
}
Upvotes: 4