从简单字符串创建层次结构 (PHP)
我在数据库中有一些字符串:x,y,z,x1,x2,x12,x22,x23,y1,y2,y3,z1,z2(不要从字面上理解它们)。
根据这些字符串,并具有一些分类规则(字符串 x1、x2 和 x3 “属于”字符串 x),我想构建某种包含这些分类规则的 OOP-ish。
x
x1
x12
x2
x22
x23
y
y1
y2
y3
z
z1
z2
基本上,我想用纯字符串制作一个菜单,了解它们的关系。
我的问题是:存储它们彼此之间的关系的最佳方法是什么,以便我可以在该层次结构中查明它们的确切“位置”?有没有适合这个问题的设计模式?我认为实体具有某些属性“深度”或“类型”。
I have some strings in a DB: x, y, z, x1, x2, x12, x22, x23, y1, y2, y3, z1, z2 (don't take them literally).
From those strings, and having some rules of classification (strings x1, x2 and x3 "belong" to string x), I want to build some kind of OOP-ish that incorporates those rules of classification.
x
x1
x12
x2
x22
x23
y
y1
y2
y3
z
z1
z2
Basically, I want to make a menu from plain strings, knowing their relation.
My question is: what is the best method to store their relation to each other, so that I can pin-point their exact "location" within this hierarchy? Is there a design pattern that suits this problem? I though of entities having some property "depth" or "type".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将菜单项存储在具有以下列的表中:
id、title、parent_id
在 PHP 中,您将能够拥有对象:
您将使用子项的 ID 作为键将子项存储在数组中:
从数据库加载时,您将通过在其中插入菜单项来构建菜单。只需在 MenuItem 对象中添加一个插入函数即可:
You could store menu items within a table having columns:
id, title, parent_id
In PHP, you would then be able to have objects:
You'll store children in the array using their ID as a key:
When loading from the DB, you'll build your menu by inserting menu items in it. Simply have an insert function within the MenuItem object:
'5:(x23,3)' 表示节点 5 是节点 3 的子节点并包含 'x23'。
'0:(x,null)' 表示节点 0 是没有父节点的顶级节点。
该数据结构可以通过包含具有两个元素的数组的数值数组来建模。
你必须递归地解析该树。
'5:(x23,3)' means node 5 is a child of node 3 and contains 'x23'.
'0:(x,null)' means that node 0 is a top-node with no parent node.
this data-structure could be modeled by an numerical array that contains an array with two elements.
you have to parse that tree recursively.
一种方法是在表中添加
parent_id
列。对于每条记录,都有一个值为 0 的父记录或其他记录的主 ID。一旦有了这个,您就可以编写一个递归函数来解析树。One way to do this is by adding a
parent_id
column in the table. For each record, there will be a parent with value 0 or the primary id of some other record. Once you have this, you can write a recursive function to parse the tree.您可以将这些值组织在一个表格中,例如嵌套集树(http://www.edutech.ch/contribution/nstrees/index.php),然后很容易找到所有子项或父项
you can organize these values in a table like a nested set tree (http://www.edutech.ch/contribution/nstrees/index.php), and then is fairly easy to find all children, or a parent