首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >类别层次结构(PHP/MySQL)

类别层次结构(PHP/MySQL)
EN

Stack Overflow用户
提问于 2010-12-16 00:41:35
回答 4查看 25.1K关注 0票数 17

我正在尝试从MySQL数据库中获取层次结构中的所有类别和子类别:

我的结果应该是这样(仅举个例子):

  1. Cat A
    • 子类别1
      • Sub_Sub_Cat 1
      • Sub_Sub_Cat Cat

代码语言:javascript
复制
- Sub\_Cat 2

  1. 类别B
  2. 类别C
  3. ...

MySQL代码:

代码语言:javascript
复制
CREATE TABLE IF NOT EXISTS `categories` (
   `category_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
   `parent_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT 'for sub-categories'
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;

简单地说,如何使用PHP代码将其置于层次结构中?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-12-16 00:44:35

当使用邻接列表模型时,您可以一次生成结构。

摘自One Pass Parent-Child Array Structure (Sep 2007; by Nate Weiner)

代码语言:javascript
复制
$refs = array();
$list = array();

$sql = "SELECT item_id, parent_id, name FROM items ORDER BY name";

/** @var $pdo \PDO */
$result = $pdo->query($sql);

foreach ($result as $row)
{
    $ref = & $refs[$row['item_id']];

    $ref['parent_id'] = $row['parent_id'];
    $ref['name']      = $row['name'];

    if ($row['parent_id'] == 0)
    {
        $list[$row['item_id']] = & $ref;
    }
    else
    {
        $refs[$row['parent_id']]['children'][$row['item_id']] = & $ref;
    }
}

从链接文章中,这里有一段代码片段,用于创建输出列表。它是递归的,如果一个节点有一个子节点,它会再次调用自己来构建子树。

代码语言:javascript
复制
function toUL(array $array)
{
    $html = '<ul>' . PHP_EOL;

    foreach ($array as $value)
    {
        $html .= '<li>' . $value['name'];
        if (!empty($value['children']))
        {
            $html .= toUL($value['children']);
        }
        $html .= '</li>' . PHP_EOL;
    }

    $html .= '</ul>' . PHP_EOL;

    return $html;
}

相关问题:

票数 49
EN

Stack Overflow用户

发布于 2017-06-15 13:04:01

尝试以下代码

//连接到mysql并选择db

$conn = mysqli_connect('localhost', 'user', 'password','database');

代码语言:javascript
复制
if( !empty($conn->connect_errno)) die("Error " . mysqli_error($conn));

//call the recursive function to print category listing
category_tree(0);

//Recursive php function
function category_tree($catid){
global $conn;

$sql = "select * from category where parent_id ='".$catid."'";
$result = $conn->query($sql);

while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '<ul>';
 echo '<li>' . $row->cat_name;
 category_tree($row->id);
 echo '</li>';
$i++;
 if ($i > 0) echo '</ul>';
endwhile;
}
//close the connection
mysqli_close($conn);
?>

More...

票数 2
EN

Stack Overflow用户

发布于 2015-06-29 10:37:06

@Amnon你的代码运行得很好。我刚刚用CodeIgniter测试了一下,它的效果很不错。如果任何人需要它,下面是工作代码:

代码语言:javascript
复制
<?php

function disTree($all_cats) {
$tree = array();
foreach ($all_cats as $cat)
{
    $pid  = $cat->parent_id;
    $id   = $cat->cat_id;
    $name = $cat->cat_name;

    // Create or add child information to the parent node
    if (isset($tree[$pid]))
        // a node for the parent exists
        // add another child id to this parent
        $tree[$pid]["children"][] = $id;
    else
        // create the first child to this parent
        $tree[$pid] = array("children"=>array($id));

    // Create or add name information for current node
    if (isset($tree[$id]))
        // a node for the id exists:
        // set the name of current node
        $tree[$id]["name"] = $name;
    else
        // create the current node and give it a name
        $tree[$id] = array( "name"=>$name );
}
return $tree;
}


function toUL($tree, $id, $html){
  $html .= '<ul>'.PHP_EOL;

  if (isset($tree[$id]['name']))
    $html .= '<li>' . $tree[$id]['name'];

  if (isset($tree[$id]['children']))
  {
    $arChildren = &$tree[$id]['children'];
    $len = count($arChildren);
    for ($i=0; $i<$len; $i++) {
        $html .= toUL($tree, $arChildren[$i], "");
    }
    $html .= '</li>'.PHP_EOL;
  }

  $html .= '</ul>'.PHP_EOL;
  return $html;
}

$tree = disTree($all_cats);
// Display the tree
echo toUL($tree, 0, "");

?>

我唯一改变的是添加了我自己的数组($all_cats)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4452472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档