显示分层数据 [英] Display hierarchical data

查看:95
本文介绍了显示分层数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个我在这里找到的有关树菜单"的代码示例,并想提出这个问题.

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` from `table` WHERE `id_parrent` = '$id'";
$result = mysql_query($query);
 if(mysql_num_rows($result) != 0)
   {
        echo "<ul>";
        while($row = mysql_fetch_array($result))
        {             
             echo "<li>",$row[name],"</li>";
             tree($row[id]);
        }
        echo "</ul>";
   }
}

如果我想以这种方式显示项目怎么办:

what if i want to display items in a way like this:

<ul>
<li>item 1</li>
<li>item 2</li>
  <li style="padding-left:10px;">item 3-has parent 2</li>
   <li style="padding-left:20px;">item 4-has parent 3</li>
  <li style="padding-left:10px;">item 5-has parent 2</li>
<li>item 6</li>
</ul>

我的主要问题是以某种方式找到级别,以便我可以乘以级别*填充并创建我的列表. 任何建议,将不胜感激.

My main problem is to find the level somehow so that i could multiply level*padding and create my list. Any suggestions would be appreciated.

推荐答案

您需要使用tree函数跟踪级别,然后在级别大于1时应用填充.

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>";
    }
}

这篇关于显示分层数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆