如何从不同的数组中获取随机值

时间:2018-08-09 11:28:27

标签: php arrays

我想从各种数组中提取数据,并想知道如何最好地做到这一点。

现在我有

$array1 = ['A', 'B', 'C', 'D', 'E'];
$array2 = ['Q', 'W', 'P', 'R', 'T', 'Y'];
$array3 = ['Z', 'X', 'V', 'N'];

$maxResults = 11;
$numberOfArrays = 3;
$inGroup = ceil($maxResults / $numberOfArrays); // 4

这里最重要的条件是,除了最后一个表之外,每个表都应获取相等数量的数据。

我想收到例如:

$results = ['A', 'B', 'C', 'D', 'Q', 'W', 'P', 'R', 'Z', 'X', 'V'];

2 个答案:

答案 0 :(得分:1)

我不完全知道您需要从最后一个数组中取出多少,但是我使用了两个(表示将从最后一个数组中选择3个元素)。我从您的问题中了解到的是您的问题的答案。

    <?php
    $array1 = ['A', 'B', 'C', 'D', 'E'];
    $array2 = ['Q', 'W', 'P', 'R', 'T', 'Y'];
    $array3 = ['Z', 'X', 'V', 'N'];

    $maxResults = 11;
    $numberOfArrays = 3;
    $inGroup = ceil($maxResults / $numberOfArrays); // 4

    $arrays = array($array1, $array2, $array3);


    function draw_data($arrays, $inGroup, $maxResults){
        $str = array();
        $arraysLength = count($arrays);
        for($i=0; $i< $arraysLength; $i++){

            if($i == $arraysLength){ /*If it is the last array */
                /*
                * This part is actually not clear in the question so I'm guessing you need to take 2 element of the last array so 
                */

                if(count($arrays[$i]) >= 2){
                    for($j = 0; $j < 2; $j++){
                        $rand = rand(0, 2); /* because array is 0 based index */
                        if(count($str)<$maxResults){
                            $str[] = $arrays[$i][$rand];
                        }
                    }
                }

            }else{ /*If not the last array */

                /* so that we don't get an index out of bound exception 
                * e.g $array2 = ['Q', 'W', 'P'] and $inGroup is 4 we can't get 4 elements from $array2 
                */

                if(count($arrays[$i]) >= $inGroup){
                    for($j = 0; $j < $inGroup; $j++){
                        $rand = rand(0, $inGroup-1); /* because array is 0 based index */
                        if(count($str)<$maxResults){
                            $str[] = $arrays[$i][$rand];
                        }
                    }
                }
            }

        }

        return $str;
    }

    print_r(json_encode(draw_data($arrays, $inGroup,$maxResults)));
?>

结果

[“ A”,“ C”,“ A”,“ D”,“ W”,“ Q”,“ W”,“ R”,“ Z”,“ Z”,“ N”]

答案 1 :(得分:0)

    shuffle($array1);
    shuffle($array2);
    shuffle($array3);
    $a1 = array_slice($array1,0, rand(0,count($array1)));
    $a2 = array_slice($array2,0, rand(0,count($array2)));
    $a3 = array_slice($array3,0, rand(0,count($array3)));
    $rand = array_merge($a1,$a2,$a3);