Php 从postgresql获取树结构数据

Php 从postgresql获取树结构数据,php,database,postgresql,Php,Database,Postgresql,我正在弄清楚哪种方法是获取树结构数据的有效方法 我有一张这样的桌子 表:食品类别 ---------------------------------------------------------- | id | parent | category_name | ---------------------------------------------------------- | 1 0 Food

我正在弄清楚哪种方法是获取树结构数据的有效方法

我有一张这样的桌子

表:食品类别

----------------------------------------------------------
| id     | parent       | category_name                  |
----------------------------------------------------------
| 1        0              Food                           |
| 2        1              Veg Items                      |
| 3        1              Non Veg Items                  |
| 4        2              Carrots                        |
| 5        2              Greens                         |
| 6        2              Milk                           |
| 7        3              Poultry                        |
| 8        3              Seafood                        |
| 9        7              Chicken                        |
| 10       8              Fish                           |
| 11       8              Prawns                         |
----------------------------------------------------------
树结构的深度在这里不受限制,它可以达到任何级别

我想把这些像下面一样拿来

array(Food'=>array( 'Veg Items'=>array('carrots'=>array(),'Greens'=>array(),'Milk'=>array()),
                    'Non Veg Items'=>array(
                                            'Poultry'=>array('Chicken'=>array()),
                                            'Seafood'=>array('Fish'=>array(),'Prawns'=>array())
                                            )
                                    )
)
这是否可以获取这种结构化数组

我在使用postgresql,但我在这方面不是很在行,在SO和其他解释类似概念的文章中,我读了很多问题,但我无法得到确切的答案


非常感谢您的帮助。

在Postgres中,您可以通过递归CTE来实现这一点:

WITH RECURISVE recCTE AS
(
    --Recursive seed
    SELECT
        parent,
        id as child,
        0 as depth
        parent || '>' || id as path
    FROM
        food_categories
    WHERE parent = 0 --restricting to the top most node of your hierarchy

    UNION ALL

    --Recursive statement
    SELECT
        recCTE.child as Parent,
        fc.id as child,
        recCTE.depth + 1 as Depth,
        path || '>' || fc.id as path
    FROM
        recCTE 
        INNER JOIN food_categories fc 
            ON recCTE.child = fc.parent
    WHERE
        depth <=20 --Set this just in case we get into an infinite cycle
)

SELECT * FROM recCTE;
带有循环记录作为
(
--递归种子
挑选
父母亲
我还是个孩子,
0作为深度
父项| |“>”| | id作为路径
从…起
食物类别
其中parent=0——限制到层次结构的最顶层节点
联合所有
--递归语句
挑选
将子对象作为父对象,
作为孩子,
将深度+1记为深度,
路径| |'>'| | fc.id作为路径
从…起
记录
内部连接食品类别fc
ON recCTE.child=fc.parent
哪里
深度可能重复的