php-递归函数类别数据库
作者:互联网
我希望创建一个我还没有想法的递归函数
这是我的代码以从数据库中获取类别
<?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>";
}
?>
目前看起来像
Top Category (category_id = 1)
Category
Sub Category
我的代码适用于类别&子类别.我打算做的是使我的代码支持无限的子类别
欢迎任何帮助和建议.
谢谢
解决方法:
我会做 :
<?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();
?>
标签:hierarchical-data,mysql,php 来源: https://codeday.me/bug/20191106/1998839.html