laurent
laurent

Reputation: 90804

uksort() function not working

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?

Upvotes: 1

Views: 2119

Answers (3)

ajuchacko91
ajuchacko91

Reputation: 1711

This is how you can use usort to sort this array the way you want it.

class Test {
   private $myArray = [];

  public function __construct()
  {
    $this->myArray = [
         array("voteCount" => 1),
         array("voteCount" => 4),
         array("voteCount" => 9),
         array("voteCount" => 2),
         array("voteCount" => 3)
     ];
   }

  private function sortByVote($a, $b)
  {
    return $a <=> $b;
  }

  public function myArray()
  {
    return $this->myArray;
  }

  public function mySort()
  {
    return usort($this->myArray, 'Test::sortByVote');
  }

}

$t = new Test;
$t->mySort();

$result = $t->myArray();

Result:

Array
(
[0] => Array
    (
        [voteCount] => 1
    )

[1] => Array
    (
        [voteCount] => 2
    )

[2] => Array
    (
        [voteCount] => 3
    )

[3] => Array
    (
        [voteCount] => 4
    )

[4] => Array
    (
        [voteCount] => 9
    )

)

Upvotes: 0

Magicianeer
Magicianeer

Reputation: 2180

You need usort() (user sort by values), not uksort() (user sort by keys) uksort's callback receives the keys of elements in $temp usort's callback receives the values of elements in $temp

Upvotes: 1

Wiseguy
Wiseguy

Reputation: 20873

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 using usort(). Or, if you're looking to maintain index association but still sort by the values, you're looking for uasort(). In short, your sort is borked.

Upvotes: 2

Related Questions