SELECT `cat`.`id` AS `catId`, `cat`.`title` AS `catTitle`, `subcat`.`title` AS `subcatTitle`
FROM `categories` AS `cat`
LEFT JOIN `subcategories` AS `subcat` ON `cat`.`id` = `subcat`.`cat_id`
ORDER BY `cat`.`id`
<?php
$cat = -1;
foreach ($result as $row) {
if ($row['catId'] != $cat) {
echo ($cat == -1 ? "" : "<\li>")."<li><p class='categories'>{$row['catTitle']}</p>";
$cat = $row['catId'];
}
echo "<p class='subcats'>{$row['subcatTitle']}</p>";
}
if ($cat != -1)
echo "</li>";
?>