Sort query result random but with a certain rules (usort)

151 views Asked by At

I'm getting an array ( mysql_fetch_assoc() ) of rooms as the result of a mysql query. I want to order this array 'randomly' but with one rule. Each room number can not be more than 2 higher or lower than the next.

Now I assume I should use usort to do this but I can't seem to figure it out. I've looked at a number of questions and explanations of usort but I simply can't get it right. I'm sure this can't be as difficult as I'm currently experiencing it to be...

This is what I'm trying right now.

shuffle($room_array);

function cmp($a, $b){
    if ($a["room"] == $b["room"] || $a["room"]+2 == $b["room"]|| $a["room"]+1 == $b["room"]|| $a["room"]-2 == $b["room"]|| $a["room"]-1 == $b["room"]){
   return 1;
   }else return 0;
}

usort($room_array, "cmp");

Thanks so much!

1

There are 1 answers

5
thecodeparadox On

Try this:

function cmp ($a, $b){
    return $b - $a; 
}
usort($room_array, 'cmp');