php category, sub category tree

前端 未结 3 1415
别跟我提以往
别跟我提以往 2021-01-23 10:29

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              


        
3条回答
  •  鱼传尺愫
    2021-01-23 11:23

    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

提交回复
热议问题