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

问题描述 投票:-3回答:2

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

我现在有:

$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'];
php arrays
2个回答
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”]


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);
© www.soinside.com 2019 - 2024. All rights reserved.