Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

php - recursive function category database

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...