Monday, 9 September 2013

Sorting array of n objects - uasort and sort

Sorting array of n objects - uasort and sort

i get data from a database which results in array with unlimited objects
which look like this (example given with 2 objects, but there can be
more):
array(2)
{
[0] object(stdClass)#34 (6)
{
["id"] string(2) "32"
["voting_id"] string(2) "42"
["answer"] string(4) "No"
["color"] string(7) "#F7464A"
["votes"] string(1) "1"
["percentage"] float(0.166666666667)
}
[1] object(stdClass)#33 (6)
{
["id"] string(2) "31"
["voting_id"] string(2) "42"
["answer"] string(2) "Yes"
["color"] string(7) "#E2EAE9"
["votes"] string(1) "5"
["percentage"] float(0.833333333333)
}
}
I want to sort this array either by votes or by percentage asc/desc. I
tried it with:
function sorterVotes($a, $b) {
if ( $a->votes < $b->votes ) return -1;
if ( $a->votes > $b->votes ) return 1;
return 0;
}
usort($answers, 'sorterVotes');
var_dump($answers);
But the only thing that gets sorted is that the [0] and the [1] changes,
but this is not helpful for me because i go through that array via foreach
later. How can i sort this array of n objects by votes / percentage and
asc/desc?
Would be great if anybody can help. Thanks.

No comments:

Post a Comment