 <p>The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.</p> <pre><code>$subjects = array(); $q = mysql_query("Select staff_id from my_table"); while($row = mysql_fetch_array($q)){ if ($subjects[$row['SUBJECT']] == nil) { $subjects[$row['SUBJECT']] = array(); } array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']); } foreach ($subjects as $key=&gt;$value) { echo $key . '&lt;br&gt;; foreach ($vaue as &amp;$staff) { echo $staff . '&lt;br&gt;'; } } </code></pre>