[英]Sort query result random but with a certain rules (usort)
I'm getting an array ( mysql_fetch_assoc() ) of rooms as the result of a mysql query. 由于mysql查询,我得到了一个房间数组(mysql_fetch_assoc())。 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. 每个房间号不能比下一个房间高2个或更低。
Now I assume I should use usort to do this but I can't seem to figure it out. 现在,我假设我应该使用usort来执行此操作,但似乎无法弄清楚。 I've looked at a number of questions and explanations of usort but I simply can't get it right. 我查看了关于usort的许多问题和解释,但我完全无法正确理解。 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! 非常感谢!
Try this: 尝试这个:
function cmp ($a, $b){
return $b - $a;
}
usort($room_array, 'cmp');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.