我在表t1
中的数据如下(只有2条记录),
+-----------+-----------------+----------+
| shid | lvlmin | lvlmax |
+-----------+-----------------+----------+
| 1 | 1 | 10 |
| 2 | 5 | 10 |
+----------------------------------------+
我的 php 代码是:
$userinfo[0] = '9';
$ghunt = DB::fetch_all("SELECT shid FROM t1
WHERE lvlmin <= ".$userinfo[0]." AND lvlmax >= ".$userinfo[0].
"ORDER BY rand() LIMIT 5");
print_r($ghunt);
结果得到2个数组:
数组 ( [0] => 数组 ( [shid] => 2 ) [1] => 数组 ( [shid] => 1 ) )
mysql查询时数组结果小于LIMIT 5
时,自动使用$ghunt
中的数组结果来填充数组怎么办?
我的意思是:
Array (
[0] => Array ( [shid] => 2 )
[1] => Array ( [shid] => 1 )
[2] => Array ( [shid] => 2 )
[3] => Array ( [shid] => 1 )
[4] => Array ( [shid] => 1 )
)
shid
可以是数组中的随机位置。
最佳答案
你为什么不做这样的事情呢?
If (count($ghunt) < 5){
$realResultCount = count($ghunt);
for ($i = realResultCount; $i <= 5; $i++){
$ghunt[$i] = $ghunt[rand(0,realResultCount-1)];
}
}
基本上,上面代码的作用是,如果 ghunt 中的记录少于 5 条,它会通过从最初返回的记录中随机选择记录来将其增加到 5 条。
关于php - 如何允许数组中重复的mysql行id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958374/