如何从索引范围中随机化数组?

我目前正在分配房间,如何将数组从索引 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);

     }


SMILET
浏览 100回答 2
2回答

慕森卡

您可以将数组拆分为两部分。随机播放第一部分并保持第二部分不变。合并这两个部分以获得您的结果。片段:<?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));演示: https ://3v4l.org/HVMc8

猛跑小猪

您可以使用这个简单的函数来检索您想要的输出:function arrayRangeRand(&$arr, $s, $e){&nbsp; &nbsp; $tmp = [];&nbsp; &nbsp; for($i=$s;$i<=$e;$i++){&nbsp; &nbsp; &nbsp; &nbsp; $tmp[] = $arr[$i];&nbsp; &nbsp; }&nbsp; &nbsp; shuffle($tmp);&nbsp; &nbsp; foreach($tmp as $ind=>$val){&nbsp; &nbsp; &nbsp; &nbsp; $arr[$s+$ind] = $val;&nbsp; &nbsp; }&nbsp;&nbsp;}&nbsp;arrayRangeRand($data, $firstInd, $lastInd0);这里for循环收集值from-to,然后将它们打乱,然后用引用索引的新值替换旧值。&改变你的原始数据数组,所以,你不需要返回任何东西。
打开App,查看更多内容
随时随地看视频慕课网APP