Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从索引范围中随机化数组?_Php_Arrays_Random - Fatal编程技术网

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

Php 如何从索引范围中随机化数组?,php,arrays,random,Php,Arrays,Random,我目前正在分配房间,如何将数组从索引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

我目前正在分配房间,如何将数组从索引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);
     }
$arrayroom=数组(“1”、“2”、“3”、“4”);
$check1=“选择COUNT(*)作为7年级的总计,其中房间号='1';
$ch=mysqli\u查询($conn,$check1);
$d=mysqli\u fetch\u assoc($ch);
如果($d[‘总计’]<40){
$room=$arrayroom[0];
}
否则{
$room=阵列随机数($arrayroom);
}
  • 可以将阵列拆分为两部分
  • 洗牌第一部分,保持第二部分原样
  • 合并两个部分以获得结果
片段:

<?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));

您可以使用此简单函数检索所需的输出:

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);
函数arrayRangeRand(&$arr,$s,$e){
$tmp=[];
对于($i=$s;$i$val){
$arr[$s+$ind]=$val;
}  
}
arrayRangeRand($data、$firstInd、$lastInd0);

这里的
for
循环从到收集值
,然后将它们洗牌,然后用引用索引的新值替换旧值
&
改变原始数据数组,因此无需返回任何内容