php 如何从数组中获取随机值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1643431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get random value out of an array?
提问by Elitmiar
I have an array called $ran = array(1,2,3,4);
我有一个名为的数组 $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
我需要从这个数组中获取一个随机值并将其存储在一个变量中,我该怎么做?
回答by reko_t
You can also do just:
你也可以只做:
$k = array_rand($array);
$v = $array[$k];
This is the way to do it when you have an associative array.
当你有一个关联数组时,这是这样做的方法。
回答by NDM
PHP provides a function just for that: array_rand()
http://php.net/manual/en/function.array-rand.php
PHP为此提供了一个函数:array_rand()
http://php.net/manual/en/function.array-rand.php
$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
回答by ólafur Waage
回答by KAS
$value = $array[array_rand($array)];
回答by Jake
You could use the array_rand function to select a random key from your array like below.
您可以使用 array_rand 函数从数组中选择一个随机键,如下所示。
$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];
or you could use the rand and count functions to select a random index.
或者您可以使用 rand 和 count 函数来选择一个随机索引。
$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];
回答by Gras Double
Derived from Laravel Collection::random():
源自 Laravel Collection::random():
function array_random($array, $amount = 1)
{
$keys = array_rand($array, $amount);
if ($amount == 1) {
return $array[$keys];
}
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
Usage:
用法:
$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];
array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']
A few notes:
一些注意事项:
$amounthas to be less than or equal tocount($array).array_rand()doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Useshuffle()afterwards if needed.
$amount必须小于或等于count($array)。array_rand()不随机键(自 PHP 5.2.10 起,请参阅48224),因此您选择的项目将始终按原始顺序排列。shuffle()如果需要,请稍后使用。
Documentation: array_rand(), shuffle()
edit:The Laravel function has noticeably grown since then, see Laravel 5.4's Arr::random(). Here is something more elaborate, derived from the grown-up Laravel function:
编辑:Laravel 功能从那时起明显增长,请参阅 Laravel 5.4 的Arr::random(). 这里有一些更复杂的东西,源自成熟的 Laravel 函数:
function array_random($array, $number = null)
{
$requested = ($number === null) ? 1 : $number;
$count = count($array);
if ($requested > $count) {
throw new \RangeException(
"You requested {$requested} items, but there are only {$count} items available."
);
}
if ($number === null) {
return $array[array_rand($array)];
}
if ((int) $number === 0) {
return [];
}
$keys = (array) array_rand($array, $number);
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
A few highlights:
几个亮点:
回答by Asciiom
The array_randfunction seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffleon the array and then taking the first element doesn't have this problem:
该array_rand函数似乎在大型数组上分布不均匀,并非每个数组项都同样有可能被选中。在数组上使用shuffle然后取第一个元素没有这个问题:
$myArray = array(1, 2, 3, 4, 5);
// Random shuffle
shuffle($myArray);
// First element is random now
$randomValue = $myArray[0];
回答by Smartpal
Another approach through flipping array to get direct value.
另一种方法是通过翻转数组来获得直接值。
Snippet
片段
$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));
array_randreturn key not value. So, we're flipping value as key.
array_rand返回键不是值。因此,我们将值翻转为键。
Note:PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.
注意:PHP key 永远是唯一的 key,所以当数组被翻转时,作为 key 的重复值将被覆盖。
回答by Duroth
$rand = rand(1,4);
or, for arrays specifically:
或者,特别是对于数组:
$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
回答by CN Lee
In my case, I have to get 2 values what are objects. I share this simple solution.
就我而言,我必须获得 2 个值,什么是对象。我分享这个简单的解决方案。
$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));

