php category, sub category tree

前端 未结 3 1413
别跟我提以往
别跟我提以往 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:08

    The result of INNER JOIN is:

    Parent Cat 1 subcategory 1
    Parent Cat 1 subcategory 2
    Parent Cat 2 subcategory 3
    

    If you want format them as array in array use php

    0 讨论(0)
  • 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 '<h1>'.htmlentities($rowCategories['parent_name']).'</h1>';
    $currentParent = $rowCategories['pid'];
    }
    
    echo '<p>' . htmlentities($rowCategories['category_name']) . '</p>';
    
    }
    

    Above code will output it like as

    <h1>Parent Cat 1</h1>
        <p>subcategory 1</p>
        <p>subcategory 2</p>
    <h1>Parent cat 2</h1>
        <p> subcategory 3</p>
    

    Edit @eggyal's comments there are some corrections to the answer

    0 讨论(0)
  • 2021-01-23 11:24
    $qry = $conn->prepare('
      SELECT   a.pid, a.parent_name, b.category_name
      FROM     parent_categories a
          JOIN child_categories  b ON a.pid = b.lpid
      ORDER BY a.pid
    ');
    
    if ($qry->execute()) {
      echo '<ul>';
    
      $row = $qry->fetch();
      while ($row) {
        $current_pid = $row['pid'];
    
        echo '<li>', htmlentities($row['parent_name']), '<ul>';
        do {
          echo '<li>', htmlentities($row['category_name']), '</li>';
        } while ($row = $qry->fetch() and $row['pid'] == $current_pid);
        echo '</ul></li>';
      }
    
      echo '</ul>';
    }
    
    0 讨论(0)
提交回复
热议问题