This code can help you.
The logic is as follows: we assume that the array is already ordered, so we focus on extracting the first character of each element of the array, when we have it, we store it and review it in each iteration, when we see a change we make a new div.
$tmp = "";
$band = false;
while ($row = $query -> result()) {
// esta condicipon solo es para la primera iteración
if (!$band):
$tmp = substr($row['title'], 0, 1);;
echo "<div style='border: 1px dotted gray; margin: 3px;'>";
echo "<h1>Letra ".$tmp."</a>";
echo "<p>";
$band = true;
endif;
// extraer la primera letra de title
$init = substr($row['title'], 0, 1);
if ($tmp === $init):
echo "<h3>".$row['title']."</h3>";
else:
$tmp = $init;
echo "</p></div>";
echo "<div style='border: 1px dotted gray; margin: 3px;'>";
echo "<h1>Letra ".$init."</h1><p>";
echo "<h3>".$row['title']."</h3>";
endif;
}
echo "</p></div>";