Hi All,
I have a table 'names' with a column 'name'.
Using a SELECT statement I've got 10,000 randomized names.

I'd like to put them into groups of 3 and have the 1 remaining name available to do something with later.

Can anybody help with the code for sorting these results into groups please?

Regards

Taffd

Dani AI

Generated

A practical choice is between doing the grouping in SQL (one pass, useful if wanting group ids stored by the database) or doing it in PHP after pulling the rows (simpler and fast enough for tens of thousands). ’s streaming loop is a valid start; the two alternatives below simplify that idea and make remainder handling explicit.

Database-side (MySQL 8+): use a window function to assign a row number in random order and derive a group id. This returns a stable group id for each row so groups can be inserted or queried directly.

-- MySQL 8+: group id = 0,1,2...
SELECT name,
       FLOOR((ROW_NUMBER() OVER (ORDER BY RAND()) - 1) / 3) AS group_id
FROM names;

ORDER BY RAND() is fine for moderate sizes but can be slow on very large tables; see MySQL window functions and RAND notes for details (window functions, RAND() docs). For huge tables, consider sampling IDs or shuffling an ID list rather than full-table RAND().

Application-side (PHP): fetch the name list (or just IDs), shuffle it, then split into chunks of 3. The last chunk is the remainder if its size < 3.

<?php
$names = $pdo->query('SELECT name FROM names')->fetchAll(PDO::FETCH_COLUMN);
shuffle($names);                     // random order
$groups = array_chunk($names, 3);    // groups of 3
$remainder = (count($names) % 3) ? array_pop($groups) : [];
?>

array_chunk and shuffle simplify the code and reduce bugs compared with manual counters.

For iterative rounds: persist groups and their round number (tables: groups, group_members). After each round pick the winners (one per group), append any remainder to the winners list for the next round, then repeat until the target council size is reached. Persisting each round and its metadata makes audits and re-runs easier and avoids accidental reseeding of randomness.

Recommended Answers

All 5 Replies

what do you mean groups? you need to go into more detail.

kkeith29,
I have 10,000 names. I wish to put them into groups of 3 names. That is 3,333 groups with 3 names in each.
There will be 1 name left over.

In the future, each group of 3 will select 1 name to represent their group.

I will thus have 3,334 names(the remaining 1 from the first level will be added)

I will then generate further groups of 3, along with any remainder.

I will continue this process, until I arrive at a number of names between about 25 and 200, depending on what I want the final group to consist of.

The code I'm after is to divide the 10,000 into groups of 3 and give me the remainder.

Taffd

how do you want the results. tabular or array ???????

Hi again kkeith,
I'm not sure what you mean by array but it's academic.
This'll be a 'behind the scenes' thing. To give you the full picture:-

This is a method of choosing leaders from an imaginary population, where the governence is largely web-based.
At the first level the electorate is split into groups of 3, who each choose a rep. These reps are again put into groups of 3 and again choose a rep. The process continues until I've got a final 'council' of say, 28 or thereabouts.
I'd envisaged a scenario where the computer selected random groups of 3, who would then be emailed to explain their groups and the closing date for choosing their rep.
The method of selecting the groups is what I'm after. Displaying any results, I can fiddle around with.

Taffd

I am not sure if this is what you are after. This is pretty complicated. You need some way of saving the groups

<?php

$host = ''; //Host
$user = ''; //Mysql Username
$pass = ''; //Mysql Password
$db   = ''; //Database Name

$con  = mysql_connect($host,$user,$pass) or die('Error: Could not connect');
mysql_select_db($db);

$sql = "SELECT * FROM `names`";
$query = mysql_query($sql, $con);
$num = mysql_num_rows($query);
if ($num > 0) {
	$names = array();
	$i = 1;
	while ($row = mysql_fetch_assoc($query)) {
		if ($i == 3) {
			//process $names array here, maybe insert into mysql table to save groups
			$names = array();
			$i = 1;
		}
		$names[] = $row['name'];
	$i++;
	}
}

?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.