简体   繁体   English

PHP - 从MySQL数据创建嵌套数组

[英]PHP - Create a nested array from MySQL data

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? 如果没有,我应该如何设置我的桌子?

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 这里有一个关于在mysql中管理分层数据的非常好的描述: 管理分层数据这是构建嵌套数组的另一个很好的例子: 构建嵌套数组

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. 如果你要查询mutch,那么它比你现在使用的邻接模型更好。

Hope that helps. 希望有所帮助。

You won't have hierarchical data from "plain" SQL dataset, but you can write a function that will do that recursively. 您不会拥有来自“普通”SQL数据集的分层数据,但您可以编写一个递归执行此操作的函数。 I can't provide code at the moment, but you probably get the idea. 我目前无法提供代码,但您可能会得到这个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM