Home > Backend Development > PHP Tutorial > PHP里一个12成员的数组,随机挑出6/3/3个成员(不重复),然后重新赋值,有什么简洁的办法实现?

PHP里一个12成员的数组,随机挑出6/3/3个成员(不重复),然后重新赋值,有什么简洁的办法实现?

WBOY
Release: 2016-06-06 20:17:57
Original
1347 people have browsed it

假设使用这个数组

<code class="php">$arr = array("A","B","C","D","E","F","G","H","I","J","K","L");//12个成员
</code>
Copy after login
Copy after login

然后我要从中分3次,分别抽出6/3/3个成员,不能重复
然后将第一次抽出的6个成员重新赋值为"A"
将第二次抽出的3个成员重新赋值为"B"
将剩余的3个成员重新赋值为"C"

大家有什么简洁的办法实现这个过程吗?

回复内容:

假设使用这个数组

<code class="php">$arr = array("A","B","C","D","E","F","G","H","I","J","K","L");//12个成员
</code>
Copy after login
Copy after login

然后我要从中分3次,分别抽出6/3/3个成员,不能重复
然后将第一次抽出的6个成员重新赋值为"A"
将第二次抽出的3个成员重新赋值为"B"
将剩余的3个成员重新赋值为"C"

大家有什么简洁的办法实现这个过程吗?

shuffle()

<code><?php $arr = array("A","B","C","D","E","F","G","H","I","J","K","L");

/**
 * 抽取方法 
 *
 * @param  array     抽取成员的源数组
 * @param  string   抽取成员的数量
 * @return array    arr_new => 抽取后的源数组, data => 抽取的数据
 */
function fun($arr=array(), $number = '')
{
    $a  = array_rand($arr, $number);
    $data = array();
    foreach ($a as $v) {
        $data[] = $arr[$v];
    }
    $arr_new = array_diff($arr, $data);
    return array(
        'arr_new' => $arr_new,
        'data'      => $data
        );
}

// 第1次抽取6个
$res = fun($arr, 6);
$first_data = $res['data'];// 第1次抽取的结果
var_dump($first_data);

// 第2次抽取3个
$res = fun($res['arr_new'], 3);
$second_data = $res['data'];// 第2次抽取的结果
$second_arr  = $res['arr_new'];// 剩下的结果

var_dump($second_data);
var_dump($second_arr);</code>
Copy after login

多多指教

Related labels:
php
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