本文实例讲述了PHP函数shuffle()取数组若干个随机元素的方法。分享给大家供大家参考,具体如下:
有时候我们需要取数组中若干个随机元素(比如做随机推荐功能),那么PHP要如何实现呢?一个比较简单的解决方法是用PHP自带的shuffle()函数。下面举一个简单的例子:
$data[] = array(
"name" => "脚本之家",
"rank" => "40"
);
$data[] = array(
"name" => "博客园",
"rank" => "50"
);
$data[] = array(
"name" => "CSDN",
"rank" => "60"
);
$data[] = array(
"name" => "ITEYE",
"rank" => "50"
);
shuffle($data);
$i = 0;
foreach($data as $key =>$value ){
if($i
页:
[1]