1

言語 => タイプ => 製品 => などの 1 対 1 の線形ツリーがあります。言語には多くの型があり、型には多くの製品があります。

次のスタイルで配列を返す再帰関数を作成しました。

Array
(
    [0] => Array
    (
        [id] => 166
        [name] => product1
        [type] => product
        [depth] => 2
        [parent] => Array
            (
                [0] => Array
                    (
                        [id] => 165
                        [name] => default
                        [type] => type
                        [depth] => 1
                        [parent] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 1
                                        [name] => en
                                        [type] => language
                                        [depth] => 0
                                        [parent] => false

                                    )

                            )

                    )

            )

    )

)

私が欲しいのは、そのツリーをトラバースし、次のような配列を提供する再帰メソッドです。

[0] => array( 'id' => 1, 'name' => 'en'),
[1] => array( 'id' => 165, 'name' => 'default'),
[2] => array( 'id' => 166, 'name' => 'product1')

0,1,2 がその要素に等しいdepthので、データのブレッドクラムを作成できます。

ありがとうございました。

4

1 に答える 1

1

ここで重要なのは、再帰的に呼び出すことができる印刷関数を作成することです。私はこのようなものを提案します

function print_recursive($array, $depth = 0) {
    //Code to print your stuff

    //Calls the print function on the parent if it's an array
    if(is_array($array['parent'])) {
        print_recursive($array['parent'], $depth+1);
    }
}

depth パラメータはデフォルトで 0 ですが、$array['parent'] で print_recursive を呼び出すときに 1 ずつ増やします。このように、配列を深くするたびに、インクリメントされます。

于 2013-07-25T14:45:06.070 に答える