php类别,子类别树 [英] php category, sub category tree

查看:111
本文介绍了php类别,子类别树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前,我已经在很长的复杂语句中做到了这一点,但我正在尝试清理一些代码.

I've done this before in long complicated statements but I'm trying to clean up some code.

我有以下表格结构

parent_categories            child_categories
-------------------          ----------------------
|pid|category_name|          |ID|category_name|lpid|
| 01| Parent cat 1|          |01|subcategory 1| 01 |
| 02| Parent cat 2|          |02|subcategory 2| 01 |
-------------------          |03|subcategory 3| 02 |
                             ----------------------

我正在尝试回显sql结果,因此它们将采用以下格式:

I am trying to echo the sql results so they would be in this format:

Parent Cat 1
    subcategory 1
    subcategory 2
Parent cat 2
    subcategory 3

这是我正在使用的代码,但是它让位给许多结果,我仍然对循环感到困惑.

Here is the code I've working with, but its giving way to many results, I get pretty messed up with loops still.

$get_categories = "SELECT * FROM
                                parent_categories a
                            INNER JOIN
                                child_categories b
                                ON a.pid = b.lpid";

$q_get= $conn->prepare($get_categories);
$q_get->execute();
    while ($rowCategories= $q_get->fetch())
    {
        echo $rowCategories['parent_name']."<br/>";
            foreach ($rowCategories as $parent)
                {
                    echo $parent."<Br?>";
                    echo $rowCategories['category_name']. "<Br/>";
                }

    }   

谢谢

推荐答案

$qry = $conn->prepare('
  SELECT   a.pid, a.parent_name, b.category_name
  FROM     parent_categories a
      JOIN child_categories  b ON a.pid = b.lpid
  ORDER BY a.pid
');

if ($qry->execute()) {
  echo '<ul>';

  $row = $qry->fetch();
  while ($row) {
    $current_pid = $row['pid'];

    echo '<li>', htmlentities($row['parent_name']), '<ul>';
    do {
      echo '<li>', htmlentities($row['category_name']), '</li>';
    } while ($row = $qry->fetch() and $row['pid'] == $current_pid);
    echo '</ul></li>';
  }

  echo '</ul>';
}

这篇关于php类别,子类别树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆