【问题标题】:How can I get all parents of an element?我怎样才能得到一个元素的所有父母?
【发布时间】:2012-06-18 01:37:40
【问题描述】:

我有一个查询 (+php) 用于获取父级的所有子级,但现在将其翻转,这样我获取一个元素的所有父级会更有用。

表:

ID     parentID     showOrder
===============================
1      0            0
2      1            0
3      2            0
4      3            1
5      3            2
6      3            3

代码:

<?php
$structure = array();
$sql = "SELECT ID, parentID FROM table ORDER BY parentID ASC, showOrder ASC";
while ($row = fetch_row()) {
  $structure[$row['parentID']][] = $row['ID'];
}

输出:

0: [1], 1: [2], 2: [3], 3: [5,4,6]

首选结果:

0: [], 1: [0], 2: [1, 0], 3: [2, 1, 0],
4: [3, 2, 1, 0], 5: [3, 2, 1, 0], 6: [3, 2, 1, 0]

我该怎么做?

【问题讨论】:

  • 你是指祖先,而不仅仅是我认为的父母?

标签: php mysql hierarchy


【解决方案1】:

你落入了分层查询领域。

虽然 Oracle 提供了一种非常方便的方式进行处理(CONNECT BY 子句),但 mysql 没有。

点击这个链接http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/会告诉你如何通过纯mysql达到你的目标。

如果您希望仅通过 php 执行此操作,您也可以,但由于引擎切换(php/mysql 之间的通信:调用查询、返回 php 等)可能会变得昂贵,因此效率会降低经过多次迭代。

rgds.

【讨论】:

    【解决方案2】:

    如果父母总是有序的,你可以像这样保持祖先的数组:

    // initialize as empty
    $ancestors = array();
    while ($row = fetch_row()) {
        $ancestors[$row['id']] = array($row['parentid'] => $row['parentid']);
        // if the parent exists
        if (isset($ancestors[$row['parentid']])) {
            // grow ancestors by parent's ancestors
            $ancestors[$row['id']] += $ancestors[$row['parentid']];
        }
    }
    

    输出:

    Array
    (
        [1] => Array
            (
                [0] => 0
            )
    
        [2] => Array
            (
                [1] => 1
                [0] => 0
            )
    
        [3] => Array
            (
                [2] => 2
                [1] => 1
                [0] => 0
            )
    
        [4] => Array
            (
                [3] => 3
                [2] => 2
                [1] => 1
                [0] => 0
            )
    
        [5] => Array
            (
                [3] => 3
                [2] => 2
                [1] => 1
                [0] => 0
            )
    
        [6] => Array
            (
                [3] => 3
                [2] => 2
                [1] => 1
                [0] => 0
            )
    
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 2018-05-17
      • 2015-12-15
      • 2015-06-08
      • 1970-01-01
      • 2016-04-07
      相关资源
      最近更新 更多