PHP - Create a nested array from MySQL data

不羁岁月 提交于 2019-12-10 10:24:45

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5111646/php-create-a-nested-array-from-mysql-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!