Heim >Backend-Entwicklung >PHP-Tutorial >PHP里一个12成员的数组,随机挑出6/3/3个成员(不重复),然后重新赋值,有什么简洁的办法实现?
<code class="php">$arr = array("A","B","C","D","E","F","G","H","I","J","K","L");//12个成员 </code>
然后我要从中分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>
然后我要从中分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>