1

Modified Pre-Order Tree Traversal Pattern を試してみました。テスト ケース コードは期待どおりの結果を返していますが、2D 配列を多次元配列に変換して表示するのに問題があります。

これは 3 レベルのメニュー結果の例です。TAL で反復できるように、これを多次元配列に変換する必要があります。

Array
(
    [0] => Array
        (
            [CategoryID] => 1
            [ParentID] => 0
            [CategoryName] => Default Parent
            [lt] => 1
            [rt] => 14
            [tree_depth] => 1
        )

    [1] => Array
        (
            [CategoryID] => 8
            [ParentID] => 1
            [CategoryName] => SysAdmin
            [lt] => 2
            [rt] => 7
            [tree_depth] => 2
        )

    [2] => Array
        (
            [CategoryID] => 2
            [ParentID] => 8
            [CategoryName] => Linux
            [lt] => 3
            [rt] => 4
            [tree_depth] => 3
        )

    [3] => Array
        (
            [CategoryID] => 3
            [ParentID] => 8
            [CategoryName] => Windows
            [lt] => 5
            [rt] => 6
            [tree_depth] => 3
        )

    [4] => Array
        (
            [CategoryID] => 5
            [ParentID] => 1
            [CategoryName] => Code
            [lt] => 8
            [rt] => 13
            [tree_depth] => 2
        )

    [5] => Array
        (
            [CategoryID] => 6
            [ParentID] => 5
            [CategoryName] => PHP
            [lt] => 9
            [rt] => 10
            [tree_depth] => 3
        )

    [6] => Array
        (
            [CategoryID] => 7
            [ParentID] => 5
            [CategoryName] => Perl
            [lt] => 11
            [rt] => 12
            [tree_depth] => 3
        )

)

すべての親が繰り返される配列の配列である「子」キーを持つようにデータを構造化する必要があります。親/子/孫が持つことができる子の数に制限はありません。 DBMS であるため、配列の構造を変更するだけです。

ポインターは大歓迎です。usort() と array_walk_recursive を試してみましたが、役に立ちませんでした。

前もって感謝します

4

1 に答える 1

3

私は単純なforeachものがここでトリックを行うことができると思います(参照の助けを借りて):

$menu連想配列を設定し$cat_id => $element_details_anb_childrenます。

$menu = array(); $ref = array();
foreach( $tree as $d ) {
    $d['children'] = array();
    if( isset( $ref[ $d['ParentID'] ] ) ) { // we have a reference on its parent
        $ref[ $d['ParentID'] ]['children'][ $d['CategoryID'] ] = $d;
        $ref[ $d['CategoryID'] ] =& $ref[ $d['ParentID'] ]['children'][ $d['CategoryID'] ];
    } else { // we don't have a reference on its parent => put it a root level
        $menu[ $d['CategoryID'] ] = $d;
        $ref[ $d['CategoryID'] ] =& $menu[ $d['CategoryID'] ];
    }
}

これにより、2つの配列が作成されます。必要な多次元配列($menu)と、各カテゴリの参照のみを保持するフラット配列です。反復ごとに、カテゴリがすでに存在する場合はその親にネストします(これが、参照テーブルを保持する理由です)。もちろん、最初の$tree配列が順序付けられている場合(つまり、親が子の前に来る場合)にのみ機能します。

于 2009-06-22T13:03:31.623 に答える