PHP - 从 MySQL 数据创建嵌套数组
我有一些数据存储在一个表中,如下所示:
id parent_id name
1 0 Entry 1
2 0 Entry 2
3 0 Entry 3
4 1 Child of entry 1
我想将其转换为一个嵌套数组,如下所示:
array(
array(
'id' => 1,
'parent_id' => 0,
'name' => 'Entry 1',
'children' => array(...)
),
...
);
理想情况下,它需要支持无限量的嵌套(孩子与孩子)。我的表是否设置为支持此功能,如果是,我将如何使用表中的数据生成这种数组?如果没有,我应该如何设置我的桌子?
I have some data stored in a table like so:
id parent_id name
1 0 Entry 1
2 0 Entry 2
3 0 Entry 3
4 1 Child of entry 1
I want to turn it into a nested array like so:
array(
array(
'id' => 1,
'parent_id' => 0,
'name' => 'Entry 1',
'children' => array(...)
),
...
);
Ideally, it would need to support an infinite amount of nesting (children with children). Is my table set up to support this, if so, how would I generate this kind of array using the data in the table? If not, how should I set up my table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一个关于管理mysql分层数据的很好的描述:
管理分层数据
这是构建嵌套数组的另一个很好的例子:
构建嵌套数组
您可能会考虑使用 Nested Set 模型。如果您要查询很多东西,它比您现在使用的邻接模型更好。
希望有帮助。
There is a very good description of managing hierarchical data in mysql here:
managing hierarchical data
Here is another good example of building nested arrays:
building nested arrays
You may think about using the Nested Set model. If you are going to query stuff mutch it is better than the adjacency model you are using right now.
Hope that helps.
您不会从“普通”SQL 数据集中获得分层数据,但您可以编写一个函数来递归地执行此操作。我目前无法提供代码,但您可能已经明白了。
You won't have hierarchical data from "plain" SQL dataset, but you can write a function that will do that recursively. I can't provide code at the moment, but you probably get the idea.