简体   繁体   English

如何从php中的数组中获取特定数量的随机元素?

[英]How to get a specific number of random elements from an array in php?

So, I,been trying to write a code for a "Dice generator" and I want it to generate random numbers (from 1-6) ax numbers of times.所以,我一直在尝试为“骰子生成器”编写代码,我希望它生成随机数(从 1 到 6 次)斧头数。 The x number of times is given as a parameter by the user through the terminal, with this "$argc argv" function, but this is not really important. x 次数由用户通过终端作为参数给出,使用“$argc argv”函数,但这并不重要。

What I want to know is: how do I generate random values x number of times?我想知道的是:如何生成随机值 x 次?

FOR EXAMPLE:例如:

User input: 4用户输入:4

Output: 5 3 6 8输出:5 3 6 8

User input: 3用户输入:3

Output: 5 1 2输出:5 1 2

This is what I am trying to write.这就是我想要写的。 I used the array_rand function with the array as a parameter, and the number of times I want as the second parameter, but It does not work!我使用array_rand函数,以数组为参数,以我想要的次数作为第二个参数,但它不起作用! What am I not getting here?我没有得到什么?

<?php

if ($argc < 2) {
    print "You have to write at least one parameter" .PHP_EOL;
    exit(1);
}
//This is the variable that corresponds to the number of times the user will give on the Terminal as a parameter.
//$randoms = $argv[1];
$num = 3;
$diceNumbers = [1, 2, 3, 4, 5, 6];
$keys = array_rand($diceNumbers, $num);

print $diceNumbers[$keys[0]]." ".$diceNumbers[$keys[1]] .PHP_EOL;

?>

Given your use case is for a ' dice roll ' I wonder if you would be better off using a cryptographically secure random number generation function like random_int() rather than array_rand() , which is not.鉴于您的用例是用于“掷骰子”,我想知道您是否最好使用加密安全的随机数生成函数,例如random_int()而不是array_rand() ,后者不是。

You can then use a for loop for your output as you know in advance how many times you want the loop to run.然后,您可以对输出使用for循环,因为您事先知道希望循环运行多少次。

$num = 3;

for($i = 0; $i < $num; $i++){
    print random_int(1,6) . PHP_EOL;
}

The array_rand(arry, n) function returns an array with length n, composed of elements from arry. array_rand(arry, n) 函数返回一个长度为 n 的数组,由 arry 中的元素组成。 It looks like you did everything right, however when you print it you only ask for the first 2 random numbers.看起来您做的一切都正确,但是当您打印它时,您只需要前 2 个随机数。 If you want to print all of the numbers, you will need a for/foreach loop.如果要打印所有数字,则需要 for/foreach 循环。

foreach($keys as $key) {
    print $key . " ";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM