|
|
 |
array_rand (PHP 4 , PHP 5) array_rand --
从数组中随机取出一个或多个单元
说明mixed array_rand ( array input [, int num_req])
array_rand() 在你想从数组中取出一个或多个随机的单元时相当有用。它接受
input 作为输入数组和一个可选的参数
num_req,指明了你想取出多少个单元 - 如果没有指定,默认为 1。
如果你只取出一个,array_rand()
返回一个随机单元的键名,否则就返回一个包含随机键名的数组。这样你就可以随机从数组中取出键名和值。
例子 1. array_rand() 例子 |
<?php
srand ((float) microtime() * 10000000);
$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand ($input, 2);
print $input[$rand_keys[0]]."\n";
print $input[$rand_keys[1]]."\n";
?>
|
|
参见 shuffle()。
brooke at jump dot net
04-Mar-2001 08:39
It is true that array_rand() returns with the selected records in the same
order as the original array. If you want otherwise, consider shuffle() on
the result. Note that there is concern over the correctness of the
shuffle() implementation. There exists an O(n) algorithm to shuffle an
array thorougly and reliably:
$c = count($foo);
for ($i=0;
$i<$c; $i++) {
$d = mt_rand(0, $i);
$tmp =
$foo[$i];
$foo[$i] = $foo[$d];
$foo[$d] =
$tmp;
}
This, of course, assumes that your keys are sequential
and start at zero. If that's not the case, you can use array_keys() to get
a sequential map of keys, I think. The rest is left as an excersise.
| |