I\'ve done this before in long complicated statements but I\'m trying to clean up some code.
I have the following table structures
parent_categories
You need to adjust your loop and foreach loop is of no use, just play with if else to check for the parent is same or different ,the result of query will have the name of parent category in each row ,
$get_categories = "SELECT *
FROM parent_categories a
INNER JOIN child_categories b ON a.pid = b.lpid
ORDER BY a.pid";
$currentParent = false;
while ($rowCategories = $q_get->fetch())
{
if ($currentParent != $rowCategories['pid'])
{
echo ''.htmlentities($rowCategories['parent_name']).'
';
$currentParent = $rowCategories['pid'];
}
echo '' . htmlentities($rowCategories['category_name']) . '
';
}
Above code will output it like as
Parent Cat 1
subcategory 1
subcategory 2
Parent cat 2
subcategory 3
Edit @eggyal's comments there are some corrections to the answer