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

查看:36
本文介绍了从数组中选择 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 开始,您可能希望对通过 shuffle($rand_keys) 返回的键进行混洗(随机化),否则它们将始终按顺序排列(最小索引第一的).也就是说,在上面的示例中,您可以得到Neo,Trinity",但不会得到Trinity,Neo".

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."

如果随机元素的顺序不重要,那么上面的代码就足够了.

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

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

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