2

如何为递归 PHP 函数安排<ul>& ?<li>我做了如下,但不能正常工作:

<?php
echo '<ul>';
$sql = mysql_query("select * from categories where parent_id = 0");
while($rs=mysql_fetch_array($sql)){
   echo '<li>'.$rs['name'];
   echo show_subcategory(($rs['cat_id']));
   echo '</li>';
}
echo '</ul>';

function show_subcategory($category_id){
$sql = mysql_query("select * from categories where parent_id ='$category_id'");
if(mysql_num_rows()>0){
echo '<ul>';
   while($rs=mysql_fetch_array($sql)){
     echo  '<li>'.$rs['name'];
     echo show_subcategory(($rs['cat_id']));
     echo '</ul></li>';
   }
 }else{
  echo '</li>';
 }
}
?>

CREATE TABLE IF NOT EXISTS categories (
  cat_id int(11) NOT NULL AUTO_INCREMENT,
  parent_id int(11) NOT NULL DEFAULT '0',
  name varchar(20) NOT NULL,
  description text NOT NULL,
  slug varchar(50) NOT NULL,
  PRIMARY KEY (cat_id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;


INSERT INTO categories (cat_id, parent_id, name, description, slug) VALUES
(1, 0, 'programming', 'Forum ', 'programming'),
(2, 1, 'php', 'php programming', 'php'),
(3, 1, 'python', '', ''),
(4, 1, 'java', '', ''),
(5, 1, 'visual basic', '', ''),
(6, 2, 'codeigniter', '', ''),
(7, 2, 'joomla', '', '');    
4

1 回答 1

3

由于它是一个递归函数,应该输出每个类别和所有子类别的列表,因此您也可以将“顶级”父类别显示移动到其中(并通过调用show_subcategory(0);.

之后,我们可以删除子关闭</ul></li>标签,它会给我们类似的东西:

function show_subcategory($category_id){
    $sql = mysql_query("select * from categories where parent_id ='$category_id'");
    if(mysql_num_rows()>0){
        echo '<ul>';
        while($rs = mysql_fetch_array($sql)){
            echo  '<li>' . $rs['name'];
            echo show_subcategory(($rs['cat_id']));
            echo '</li>';
        }
        echo '</ul>';
    }
}

show_subcategory(0);

旁注,不具体回答:
我建议升级到MySQLiPDO扩展。两者都支持准备好的语句,可提供针对 SQL 注入攻击的安全性(您当前的代码容易受到攻击)。

于 2012-12-05T13:43:08.360 回答