Вот относительно простое решение с использованием array_reduce
:
$rows = array(
array(1, 30, 40, 22, 12, 14, 55, 68, 91, 80, 99, 23, 63, 61, 83),
array(8, 17, 59, 14, 93, 31, 57, 91, 29, 38, 54, 47, 28, 12, 15)
);
// replace this line with your while($row = $result->fetch_assoc())
foreach ($rows as $row) {
echo "<tr>";
sort($row);
$groups = array_reduce($row, function ($c, $v) { $c[(int)floor(($v-1) / 20)][] = $v; return $c; }, array());
for ($i = 0; $i < 5; $i++) {
echo "<td>" . implode(',', isset($groups[$i]) ? $groups[$i] : array()) . "</td>";
}
echo "</tr>\n";
}
Вывод:
<tr><td>1,12,14</td><td>22,23,30,40</td><td>55</td><td>61,63,68,80</td><td>83,91,99</td></tr>
<tr><td>8,12,14,15,17</td><td>28,29,31,38</td><td>47,54,57,59</td><td></td><td>91,93</td></tr>