PHP implements taking a specified number of non-duplicate sub-collections from a specified array

WBOY
Release: 2016-08-08 09:30:56
Original
1085 people have browsed it

Method one:

$arrn=array();
$arr=range(1,20);//指定的数组
$arri=array_rand($arr,6);//随机产生6个$arr数组元素的下标
foreach($arri as $k=>$v){
    $arrn[$k]=$arr[$v];
}
print_r($arrn);//输出
Copy after login

Method two:

$arrn=array();
$arr=range(1,20);//指定数组
$len=count($arr);//指定数组的长度
$count=6;//待产生数组的长度
for($i=0;$i<$count;$i++){
    $ckey=mt_rand(0,$len-$i-1);//随机获取0至 $len-$i-1之间的下标,从剩下的随机数里生成
    $tmp=$arrn[]=$arr[$ckey];//赋值给结果数组
    $arr[$ckey]=$arr[$len-$i-1];//把随机数产生过的位置替换为末尾对应未被选中的值。
        //$arr[$len-$i-1]=$tmp;
}
print_r($arrn);
Copy after login

Method three:

$arrn=array();
$arr=range(1,20);//指定数组
$len=count($arr);//指定数组的长度
$count=6;//待产生数组的长度
for($i=0;$i<$count;$i++){
    $ckey=mt_rand(0,$len-$i-1);//随机获取0至 $len-$i-1之间的下标,从剩下的随机数里生成
    $arrn[]=$arr[$ckey];//赋值给结果数组
    unset($arr[$ckey]);//删除已经获取的值
    $arr=array_values($arr);//重新建立索引
}
print_r($arrn);
Copy after login

The above introduces the PHP implementation of obtaining a specified number of non-duplicate sub-sets from a specified array, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template