5

このスペースツリーでは、ネストされたセット構造(mysql)をjsonに変換する必要があります1)http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html

入れ子集合から配列を作成するこの関数を見つけました:2)http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimension-arrays-in-php

PHP関数json_encodeを使用してphp配列をjsonに変換することもできます

私の問題:関数nestify(2番目のリンクから)は、私が必要としているものを正確に与えてくれません。私はこのようなものが必要です:http://pastebin.com/m68752352

関数「nestify」を変更して正しい配列を取得するのを手伝ってもらえますか?

この関数をもう一度示します。

function nestify( $arrs, $depth_key = 'depth' )
    {
        $nested = array();
        $depths = array();

        foreach( $arrs as $key => $arr ) {
            if( $arr[$depth_key] == 0 ) {
                $nested[$key] = $arr;
                $depths[$arr[$depth_key] + 1] = $key;
            }
            else {
                $parent =& $nested;
                for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
                    $parent =& $parent[$depths[$i]];
                }

                $parent[$key] = $arr;
                $depths[$arr[$depth_key] + 1] = $key;
            }
        }

        return $nested;
    }
4

1 に答える 1

10

次のスニペットは、私が Web で見つけたいくつかの PHP Doctrine コードから適応したトリックを行う必要があります。

function toHierarchy($collection)
{
        // Trees mapped
        $trees = array();
        $l = 0;

        if (count($collection) > 0) {
                // Node Stack. Used to help building the hierarchy
                $stack = array();

                foreach ($collection as $node) {
                        $item = $node;
                        $item['children'] = array();

                        // Number of stack items
                        $l = count($stack);

                        // Check if we're dealing with different levels
                        while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) {
                                array_pop($stack);
                                $l--;
                        }

                        // Stack is empty (we are inspecting the root)
                        if ($l == 0) {
                                // Assigning the root node
                                $i = count($trees);
                                $trees[$i] = $item;
                                $stack[] = & $trees[$i];
                        } else {
                                // Add node to parent
                                $i = count($stack[$l - 1]['children']);
                                $stack[$l - 1]['children'][$i] = $item;
                                $stack[] = & $stack[$l - 1]['children'][$i];
                        }
                }
        }

        return $trees;
}
于 2009-05-20T09:00:01.163 に答える