I’m trying to sort an array in PHP using a custom function, but it’s not working. Here is the (simplified) code I’m using:
class Test {
public function sortByVote($a, $b) {
$v1 = $a['voteCount'];
$v2 = $b['voteCount'];
if ($v1 > $v2) return +1;
if ($v1 < $v2) return -1;
return 0;
}
function test() {
$temp = array(
array("voteCount" => 1),
array("voteCount" => 4),
array("voteCount" => 9),
array("voteCount" => 2),
array("voteCount" => 3)
);
uksort($temp, array($this, "sortByVote"));
}
}
Can anybody see what the issue is?
uksort()sorts the keys. In your example, the keys are just automatically generated numeric keys from 0 – 4. I think you mean to sort by values usingusort(). Or, if you’re looking to maintain index association but still sort by the values, you’re looking foruasort(). In short, your sort is borked.