我目前正在分配房间,如何将仅从索引1到3的数组随机化?我的数组中有4个索引。
$arrayroom = array("1","2","3","4");
$check1 = "SELECT COUNT(*) AS Total FROM grade_7 WHERE Room_Number = '1' ";
$ch= mysqli_query($conn,$check1);
$d = mysqli_fetch_assoc($ch);
if($d['Total'] < 40){
$room = $arrayroom[0];
}
else{
$room = array_rand($arrayroom);
}
Snippet:
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$randomize = array_slice($input,0,3);
$keep_safe = array_slice($input,3);
shuffle($randomize);
print_r(array_merge($randomize,$keep_safe));
Demo: https://3v4l.org/HVMc8
您可以使用此简单功能检索所需的输出:
function arrayRangeRand(&$arr, $s, $e){
$tmp = [];
for($i=$s;$i<=$e;$i++){
$tmp[] = $arr[$i];
}
shuffle($tmp);
foreach($tmp as $ind=>$val){
$arr[$s+$ind] = $val;
}
}
arrayRangeRand($data, $firstInd, $lastInd0);
这里for
循环收集值from-to
,然后将它们洗牌,然后用引用的索引用新值替换旧值。 &
更改了原始数据数组,因此,您无需返回任何内容。