我怎样才能得到元素的所有父母?

时间:2012-06-18 01:37:41

标签: php mysql hierarchy

我有一个查询(+ 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]

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您正处于分层查询域中。

虽然Oracle提供了一种非常方便的方法来继续(CONNECT BY子句),但mysql没有。

点击此链接http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/将向您解释如何通过纯mysql实现目标。

如果你只想通过php做,你也可以这样做,但是因为引擎切换(php / mysql之间的通信:调用查询,回到php等等),它会以某种方式效率低下经过多次迭代。

RGDS。

答案 1 :(得分:0)

如果父母总是在秩序中,你可以像这样保留祖先阵列:

// 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
        )

)