类别层次结构(PHP/MySQL) [英] Category Hierarchy (PHP/MySQL)
本文介绍了类别层次结构(PHP/MySQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从MySQL数据库中按层次结构获取所有类别和子类别:
I am trying to get my all categories and sub-categories from MySQL database in a hierarchy:
我的结果应该是这样(仅作为示例):
My result should be like that (just example):
- 猫A
- 子类别1
- Sub_Sub_Cat 1
- Sub_Sub_Cat 2
- 子类别1
- Cat A
- Sub-Cat 1
- Sub_Sub_Cat 1
- Sub_Sub_Cat 2
- Sub-Cat 1
MySQL代码:
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代码将其添加到层次结构中?
Simply, how can get it in a hirarchy with PHP codes?
推荐答案
使用邻接表模型时,您可以一次性生成结构.
When using an adjacency list model, you can generate the structure in one pass.
来自一次通过父子数组结构(2007年9月; Nate Weiner撰写):
$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;
}
}
在链接的文章中,这是一个片段,用于创建输出列表.这是递归的,如果一个节点有一个子节点,它会再次调用自身以建立子树.
From the linked article, here's a snippet to create a list for output. It is recursive, if there a children for a node, it calls itself again to build up the subtree.
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;
}
相关问题:
这篇关于类别层次结构(PHP/MySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文