0

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

我怎样才能做到这一点?

4

2 回答 2

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
        )

)
于 2012-06-18T02:02:22.513 回答
0

您落入了分层查询域。

尽管 Oracle 提供了一种非常方便的方式来处理(CONNECT BY子句),但 mysql 没有。

按照此链接http://explainextended.com/2009/03/17/hierarchical-queries-in-mysql/将向您解释如何通过纯 mysql 达到目标。

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

rgds。

于 2012-06-18T01:43:04.427 回答