将数据平均分配到组中

I have a MySQL table with groups of people who have a number attached to their name. They are either a 1,2,3 or 4. I need to create groups where there is an even distribution of members in each group. In other words, I don't want all the 4's in one group, or all the 3's in another. I'd like it to be distributed evenly. This is what I have so far. It echo's out the people and groups them by their level, but I'm not sure how to make groups of them that equally distributes their levels. I have some more code and even though I've pissed off the community with my lack of experience, I was hoping someone might be able to tell me how to clean up the code. It works how I want it, but it feels ugly. Any help would be greatly appreciated.

<?php

include_once 'connect.php';

$level1 = array();
$level2 = array();
$level3 = array();
$level4 = array();

$sql1 = "SELECT * FROM table WHERE level = 1";
$stmt = $handler->prepare($sql1);
$stmt->execute();

$row = $stmt->fetchAll();

foreach($row as $rows)
{

$level1[] = $rows['name'];

}

$sql2 = "SELECT * FROM table WHERE level = 2";
$stmt = $handler->prepare($sql2);
$stmt->execute();

$row = $stmt->fetchAll();

foreach($row as $rows)
{

$level2[] = $rows['name'];

}

$sql3 = "SELECT * FROM table WHERE level = 3";
$stmt = $handler->prepare($sql3);
$stmt->execute();

$row = $stmt->fetchAll();

foreach($row as $rows)
{

$level3[] = $rows['name'];

}

$sql4 = "SELECT * FROM table WHERE level = 4";
$stmt = $handler->prepare($sql4);
$stmt->execute();

$row = $stmt->fetchAll();

foreach($row as $rows)
{

$level4[] = $rows['name'];

}

$sql5 = "SELECT * FROM table";
$stmt = $handler->prepare($sql5);
$stmt->execute();

$row = $stmt->fetchAll();
$result = count($row);

for($i=0; $i<=$result; $i++)
{

echo $level1[$i];
echo"<br>";
echo $level2[$i];
echo"<br>";
echo $level3[$i];
echo"<br>";
echo $level4[$i];
echo"<br>";

}

?>

Sounds like a simple round-robin style of distribution, it requires a loop range of 1 to 4, uses that as an index to an array that accumulates counts for each group. That may solve the problem you describe, if I have understood what you have asked.

If you are still in the theoretical side of this, draw a diagram of what you mean. A code example would mean the answer could address your issue rather than address it theoretically.