Display hierarchical data

后端 未结 2 1325
南旧
南旧 2021-01-15 19:05

I am playing around with a code example i found here about \'tree menu\' and wanted to make this question.

function tree($id)
{
$query = \"SELECT `name`,`id`         


        
相关标签:
2条回答
  • 2021-01-15 19:27

    I have a store with recursive inventory categories similar to what you're doing. Here's the code I wrote to present it as an unordered list (slightly modified for this example). Hope it helps!

      /**
       * Inventory Categories
       */
      function inventoryCategories() {
    
        $result = mysql_query("select * from store_inventorycategory");
    
        $rows = array();
    
        while ($row = mysql_fetch_array($result)) {
          $p = $row['parent_category_id'];
          $id = $row['id'];
          $rows[$id] = array('id'=>$id, 'parent'=>$p, 'title'=>$row['title'], 'children'=>array());
        }
    
        foreach ($rows as $k=>&$v) {
          if ($v['parent'] == $v['id']) continue;
          $rows[$v['parent']]['children'][] = &$v;
        }
    
        array_splice($rows,1);
    
        echo '<ul>';
        recurseInventoryCategory($rows[0]);
        echo '</ul>';   
      }
    
      /**
       * display inventory category tree 
       */ 
      function recurseInventoryCategory ($o) {
        echo "<li><a href='store/{$o['id']}/'>{$o['title']}</a><ul class='list_indent'>";
        foreach ($o['children'] as $v) {
          recurseInventoryCategory($v);
        }
        echo "</ul></li>";
      }
    
    0 讨论(0)
  • 2021-01-15 19:28

    You need your tree function to track the level, and then apply padding if the level is greater than 1.

    function tree($id, $level=1) {
        $query = "SELECT `name`,`id` from `table` WHERE `id_parrent` = '$id'";
        $result = mysql_query($query);
        if (mysql_num_rows($result) != 0) {
         echo "<ul>";
         while ($row = mysql_fetch_array($result)) {
             if ($level == 1)
                 echo "<li>" . $row[name] . "</li>";
             else
              echo "<li style='padding-left: " + (($level - 1) * 10) + "px;'>" . $row[name] . "</li>";
             tree($row[id], $level + 1);
         }
         echo "</ul>";
        }
    }
    
    0 讨论(0)
提交回复
热议问题