php - 在单列中管理父子层次结构

标签 php mysql

我必须进行查询以选择数据,例如父项是SFI,id为1,然后删除 Bath ,砍掉并分手是SFI的 child 和淋浴盘、 Parquet 、熨平板都是分手的 child 。

表的结构。 (SOR表)

sor_id | items       | parent_id
-------------------------
 1 | SFI         | 0
 2 | Remove bath | 1
 3 | Hack off    | 1
 4 | break up    | 1
 5 | Shower tray | 4
 6 | Timber floor| 4
 7 | screeded    | 4
 8 | general 123 | 1

所以我的问题是我们可以使用两次自连接并在 php 循环中进行一些锻炼来实现这个结果吗?

坦白说,我不知道我们是否可以用一个parent_id来管理这个层次结构,

select * from sor as m_sor 
LEFT JOIN sor as c_sor ON m_sor.sor_id = c_sor.parent_id
LEFT JOIN sor as sc_sor 0N sc_sor.sor_id = c_sor.parent_id

最佳答案

根据@RamRaider的指示,mysql不支持递归查询。而且我无法更改表结构。 所以我做了一个递归函数。 首先,我从数据库中选择了所有数据并使用下面的recursive php函数。

function buildTree( $ar, $pid = 0 ) {
            $op = array();
            foreach( $ar as $item ) {
                if( $item['parent_id'] == $pid ) {
                    $op[$item['sor_id']] = array(
                        'sor_id' => $item['sor_id'],
                        'item_no' => $item['item_no'],
                        'price' => $item['price'],
                        'base_qty' => $item['base_qty'],
                        'description' => $item['description'],
                        'type' => $item['type'],
                        'form_name' => $item['form_name'],
                        'status' => $item['status'],
                        'modified_date' => $item['modified_date'],
                        'parent_id' => $item['parent_id']
                    );
                    // using recursion
                    $children =  buildTree( $ar, $item['sor_id'] );
                    if( $children ) {
                        $op[$item['sor_id']]['children'] = $children;
                    }
                }
            }
            return $op;
}

所以,它有效并返回了我想要的结果。

关于php - 在单列中管理父子层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45096419/

相关文章:

php - 从 URL 传递变量 + 从 SQL 中选择并回显它

php - 搜索栏结果过滤器 php

php - 联合中的MySQL查询错误

mysql - 如何使用多个连接进行插入?

php - 部分渲染的 div 内的 ajax 验证

php - 查找包含特定项目的目录的最快方法

php - 计算与 IN 子句中的所有值匹配的所有行

mysql - 显示一列中相同数据的一项数据

mysql - InnoDB 和计数 : Are helper tables the way to go?

php - 具有相应输入值的复选框数组