Display hierarchical data
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开发者_StackOverflow中文版 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.
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>";
}
}
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>";
}
精彩评论