$ curl cheat.sh/
/*
 * You could use `GROUP_CONCAT()` to concatenate all subtopics into one
 * string per topic, and then parse the string in your application code.
 */

 SELECT topic_name, GROUP_CONCAT(subtopic_name DELIMITER '§§§') as subtopic_names
 FROM questions2
 GROUP BY topic_name

/*
 * But i do not recommend that, because you will get in troubles, if a
 * subtopic contains your delimiter. I would just use your second query
 * and group the result in the application code.
 * 
 * PHP code would look something like:
 * 
 * <!-- language: lang-php -->
 */

 // group the data
 $groupedData = array();
 foreach ($data as $item) {
     $topic_name = $item['topic_name'];
     $subtopic_name = ucwords($item['subtopic_name']);
     $groupedData[$topic_name][] = $subtopic_name;
 }

 // grouped output
 foreach ($groupedData as $topic_name => $subtopic_names) {
     echo '<div class="the_topic">';
     echo '<h2 class="topic_change">' . $topic_name . '</h2><ul>';
     foreach ($subtopic_names as $subtopic_name) {
         echo '<li class="subtopic_name"><a href="#" data-toggle="modal" data-target="#lvlModal"><h3>';
         echo $subtopic_name;
         echo '</h3></a></li>';
     }
     echo '</ul><hr /></div>';
 }

/* [Paul Spiegel] [so/q/39677854] [cc by-sa 3.0] */

$
Follow @igor_chubin cheat.sh