Coba
...
//Detect change in category
if($catID != $categoryId)
{
echo "<h3>Category 01: <span>{$category}</span><span></span></h3>";
echo "<div class='container'>";
echo "<table>";
if (is_array($subjects))
{
foreach ($subjects as $sub) {
echo "<tr>";
echo "<td>";
echo $sub;
echo "</td>";
echo "</tr>";
}
}
else
{
echo "<tr><td>No subjects to display...<td/><tr/>";
}
echo "</table>";
echo "</div> <!-- End .container DIV -->";
}
...
Perbarui
Berpikir untuk mengubah pendekatan yang Anda gunakan untuk mengambil data dari DB. Coba kode ini (kode tidak diuji, ketik menggunakan notepad) jadi Anda mungkin perlu sedikit memperbaikinya...)
$categoryIds = implode(',', $_SESSION['category']);
$q = "SELECT c. category_id AS ci, c.category_name AS cn
FROM category AS c
WHERE c.category_id IN ($categoryIds)";
$r = mysqli_query( $dbc, $q) ;
$catID = false;
$max_columns = 2;
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$categoryId = $row['ci'];
$category = $row['cn'];
echo '<div>';
echo "<h3>Category 01: <span>{$category}</span><span></span></h3>\n";
$qs = "SELECT s.subject_name AS sn, s.subject_id AS si
FROM category_subjects cs
INNER JOIN subjects AS s ON s.subject_id = cs.subject_id
WHERE cs.category_id = \'' . $categoryId . '\'";
$rs = mysqli_query( $dbc, $qs) ;
echo "<h3>Category 01: <span>{$category}</span><span></span></h3>";
echo "<div class='container'>";
echo "<table>";
while ($rows = mysqli_fetch_array($rs, MYSQLI_ASSOC))
{
$sub = $rows['sn'];
echo "<tr>";
echo "<td>";
echo $sub;
echo "</td>";
echo "</tr>";
}
echo "</table>";
echo "</div> <!-- End .container DIV -->";
echo '</div>';
}
Dalam hal ini kita mengambil Kategori terlebih dahulu, masuk dalam satu lingkaran, cetak nama Kategori terlebih dahulu dan dalam lingkaran tersebut kita mengambil Subjek yang sesuai untuk kategori saat ini, kemudian mencetak yang berikutnya dan seterusnya...