类别层次结构 (PHP/MySQL) [英] Category Hierarchy (PHP/MySQL)
问题描述
我正在尝试从层次结构中的 MySQL 数据库中获取我的所有类别和子类别:
我的结果应该是这样的(只是例子):
<块引用>- 猫 A
- 子类别 1
- Sub_Sub_Cat 1
- Sub_Sub_Cat 2
- Sub_Cat 2
- 子类别 1
- 猫 B
- 猫 C
- ...
MySQL 代码:
如果不存在则创建表`categories`(`category_id` mediumint(8) 无符号 NOT NULL AUTO_INCREMENT,`parent_id` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT 'for sub-categories'主键(`category_id`)) 引擎=InnoDB 默认字符集=utf8 ;
简单地说,如何使用 PHP 代码使其成为一个层次结构?
使用邻接表模型时,可以一次性生成结构.
取自 One Pass父子数组结构(2007 年 9 月;Nate Weiner 着):
$refs = array();$list = 数组();$sql = "SELECT item_id, parent_id, name FROM items ORDER BY name";/** @var $pdo \PDO */$result = $pdo->query($sql);foreach ($result 作为 $row){$ref = &$refs[$row['item_id']];$ref['parent_id'] = $row['parent_id'];$ref['name'] = $row['name'];如果($row['parent_id'] == 0){$list[$row['item_id']] = &$ref;}别的{$refs[$row['parent_id']]['children'][$row['item_id']] = &$ref;}}
从链接的文章中,这里有一个片段,用于创建输出列表.它是递归的,如果一个节点有子节点,它会再次调用自己来构建子树.
function toUL(array $array){$html = ''.PHP_EOL;foreach ($array 作为 $value){$html .='- '.$value['name'];if (!empty($value['children'])){$html .= toUL($value['children']);}$html .='
'.PHP_EOL;}$html .= '</ul>'.PHP_EOL;返回 $html;}
相关问题:
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):
- Cat A
- Sub-Cat 1
- Sub_Sub_Cat 1
- Sub_Sub_Cat 2
- Sub_Cat 2
- Cat B
- Cat C
- ...
MySQL code:
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 ;
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.
Taken from One Pass Parent-Child Array Structure (Sep 2007; by 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;
}
Related Question:
这篇关于类别层次结构 (PHP/MySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!