prepare('SELECT id,person_id FROM grp ORDER BY RAND()'); $stmt->execute(); $res = $stmt->get_result(); $raw = $res->fetch_all(MYSQLI_ASSOC); $res->free(); $stmt->close(); $con->close(); return $raw; } function init(&$onegroup, &$ingroup, &$dupl) { $onegroup = array(); $ingroup = array(); $dupl = array(); } function process_row($row, &$ingroup, &$onegroup, &$dupl, &$groups, $max) { if(array_key_exists($row['person_id'], $ingroup)) { $dupl[] = $row; } else { $onegroup[] = $row; $ingroup[$row['person_id']] = true; } if(count($onegroup) == $max) { $groups[] = $onegroup; $olddupl = $dupl; init($onegroup, $ingroup, $dupl); foreach($olddupl as $row) { process_row($row, $ingroup, $onegroup, $dupl, $groups, $max); } if(count($dupl) > 0) throw new Exception("Could not complete grouping"); } } function dogrouping($raw, $max) { $groups = array(); init($onegroup, $ingroup, $dupl); foreach($raw as $row) { process_row($row, $ingroup, $onegroup, $dupl, $groups, $max); } $olddupl = $dupl; $dupl = array(); foreach($olddupl as $row) { process_row($row, $ingroup, $onegroup, $dupl, $groups, $max); } if(count($dupl) > 0) throw new Exception("Could not complete grouping"); if(count($onegroup) > 0) { $groups[] = $onegroup; } return $groups; } $raw = loadraw(); echo "Raw:\r\n"; foreach($raw as $row) { echo $row['id'] . ' ' . $row['person_id'] . "\r\n"; } echo "\r\n"; $grouped = dogrouping($raw, 10); $gn = 1; foreach($grouped as $group) { echo "Group $gn:\r\n"; foreach($group as $row) { echo ' ' . $row['id'] . ' ' . $row['person_id'] . "\r\n"; } $gn++; } ?>