从阵列中选择3个不同的随机值 [英] Choose 3 different random values from an array

查看:113
本文介绍了从阵列中选择3个不同的随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有30个值的数组,我需要从这个数组3个不同的随机值提取。我该怎么办呢?

I have an array of 30 values and I need to extract from this array 3 different random values. How can I do it?

推荐答案

从PHP手册无耻被盗:

Shamelessly stolen from the PHP manual:

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

http://us2.php.net/array_rand

需要注意的是,由于PHP 5.2.10,你可能要重新洗牌(随机)随机($ rand_keys)正在通过返回键,否则他们将永远在顺序(最小的指数在前)。也就是说,在上面的例子中,你可以得到新三位一体但从来没有三位一体,新。

Note that, as of PHP 5.2.10, you may want to shuffle (randomize) the keys that are returned via shuffle($rand_keys), otherwise they will always be in order (smallest index first). That is, in the above example, you could get "Neo, Trinity" but never "Trinity, Neo."

如果随机元素的顺序并不重要,那么上述code是足以

If the order of the random elements is not important, then the above code is sufficient.

这篇关于从阵列中选择3个不同的随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆