php类别,子类别树

时间:2014-04-19 15:07:27

标签: php mysql

我之前在冗长复杂的陈述中做过这个,但我试图清理一些代码。

我有以下表结构

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结果,因此它们将采用以下格式:

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

这是我正在使用的代码,但是它让位给了许多结果,我对循环仍然非常混乱。

$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/>";
                }

    }   

由于

3 个答案:

答案 0 :(得分:1)

$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>';
}

答案 1 :(得分:0)

INNER JOIN的结果是:

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

如果你想将它们格式化为数组中的数组使用php

答案 2 :(得分:0)

你需要调整你的循环并且foreach循环是没有用的,只需用if else来检查父级是相同还是不同,查询的结果将在每一行中都有父类的名称,

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

$currentParent = false;
while ($rowCategories = $q_get->fetch())
{
if ($currentParent != $rowCategories['pid'])
{
echo '<h1>'.htmlentities($rowCategories['parent_name']).'</h1>';
$currentParent = $rowCategories['pid'];
}

echo '<p>' . htmlentities($rowCategories['category_name']) . '</p>';

}

上面的代码会像

一样输出
<h1>Parent Cat 1</h1>
    <p>subcategory 1</p>
    <p>subcategory 2</p>
<h1>Parent cat 2</h1>
    <p> subcategory 3</p>

编辑 @ eggyal的评论对答案有一些更正