超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<array_pusharray_reduce>
Last updated: Fri, 22 Jun 2007

array_rand

(PHP 4 , PHP 5)

array_rand --  从数组中随机取出一个或多个单元

说明

mixed array_rand ( array input [, int num_req])

array_rand() 在你想从数组中取出一个或多个随机的单元时相当有用。它接受 input 作为输入数组和一个可选的参数 num_req,指明了你想取出多少个单元 - 如果没有指定,默认为 1。

如果你只取出一个,array_rand() 返回一个随机单元的键名,否则就返回一个包含随机键名的数组。这样你就可以随机从数组中取出键名和值。

注: 在 PHP 4.2.0 中,无需用函数 srand()mt_srand()来搜寻随机数生成器,它将被自动完成。

例子 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()




add a note add a note User Contributed Notes
array_rand
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.

<array_pusharray_reduce>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22