可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
i hoping to create a recursive function which i don't have an idea yet
this is my code to fetch category from database
<?php $sql = mysql_query("SELECT * FROM categories WHERE category_parent = '1' ORDER BY lft ASC"); while($row = mysql_fetch_array($sql)) { echo "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a>"; $sql2 = mysql_query("SELECT * FROM categories WHERE category_parent = '{$row['category_id']}'"); if(mysql_num_rows($sql2) > 0) echo "<ul>"; while($row2 = mysql_fetch_array($sql2)) { echo "<li><a href='/{$row2['category_safe_name']}/'>{$row2['category_name']}</a><li>"; } if(mysql_num_rows($sql2) > 0) echo "</ul>"; echo "</li>"; } ?>
Currently This look like
Top Category (category_id = 1) Category Sub Category
My code works for category & subcategory. What i'm planning to do is to make my code to support unlimited subcategories
Any help and advise are welcomed.
Thank you
回答1:
I would do :
<?php function getChildren($id=1) { $sql = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY lft ASC"); echo "<ul>"; while($row = mysql_fetch_array($sql)) { echo "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a>"; getChildren($row['category_id']); echo "</li>"; } echo "</ul>"; } getChildren(); ?>
回答2:
You should have a look at Managing Hierarchical Data in MySQL.
It gives a good overview of some approaches to using hierarchical data in MySQL.
回答3:
What you need to do, is build a recursive function. That is, a function that calls itself within. An example:
function getCategories($parent=0) { $res = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY left ASC"); if (mysql_num_rows($res) > 0) { $category = mysql_fetch_object(); echo '<ul>'; echo '<li><a href="' . $category->category_safe_name . '">' . $category->category_name . '</a>'; getCategories($category->category_id); echo '</li>'; } }
If I've made any typos in regards to table and column names then obviously swap them out for the correct values.
回答4:
Something like this?
function getCategories($mid, $categoryParent = 1) { $return = ''; $results = mysql_query("SELECT * FROM categories WHERE category_parent = '$categoryParent' ORDER BY lft ASC", $mid); while($row = mysql_fetch_array($results)) { $return .= "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a></li>"; $subs = getCategories($mid, $row['category_id']); if (!empty($subs)) { $return .= '<ul>'; $return .= $subs; $return .= '<ul>'; } } return $return; } $mid = mysql_connect($host, $user, $pass); echo getCategories($mid);
Would print out all your categories, of course fix it to exactly how you want, but that should give you an idea of how recursive functions could work