Created
August 3, 2012 08:05
-
-
Save jqlblue/3245647 to your computer and use it in GitHub Desktop.
用户随机分组
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//将用户进行随机分组,每组6个 | |
$all = array( | |
'x1','x2','x3','x4', | |
'x5','x6','x7','x8', | |
); | |
define('GROUP_MAX', 6); | |
$groupCount = getGroupCount(count($all)); | |
$groups = initGroups($groupCount); | |
shuffle($all); | |
while(! empty($all)) { | |
$user = getRandUser(& $all); | |
$groupId = getRandGroupId($groupCount, $groups); | |
if ($groupId === false) { | |
die ('oh, what happen'); | |
} | |
$groups[$groupId][] = $user; | |
} | |
var_dump($groups); | |
// 获取分组数量 | |
function getGroupCount($count) | |
{ | |
if ($count % GROUP_MAX == 0) { | |
return $count / GROUP_MAX; | |
} | |
return intval($count / GROUP_MAX) + 1; | |
} | |
// 随机获取一个用户 | |
function getRandUser(& $users) | |
{ | |
$randKey = array_rand($users); | |
$rand = $users[$randKey]; | |
unset($users[$randKey]); | |
return $rand; | |
} | |
// 初始化分组 | |
function initGroups($count) | |
{ | |
$groups = array_fill(1, $count, array()); | |
return $groups; | |
} | |
// 随机取出一个不满的组 | |
function getRandGroupId($groupCount, $groups) | |
{ | |
$groupIds = range(1, $groupCount); | |
shuffle($groupIds); | |
foreach ($groupIds as $groupId) { | |
if (count($groups[$groupId]) < GROUP_MAX) { | |
return $groupId; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment