首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套集、php数组和转换

问嵌套集、php数组和转换
EN

Stack Overflow用户
提问于 2009-05-08 17:46:48
回答 1查看 7.4K关注 0票数 5

对于这个空间树1) http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html,我需要将我的嵌套集合结构(mysql)转换成json

我发现这个函数可以从嵌套的集合中创建数组: 2) http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimensional-arrays-in-php

我也可以用php函数json_encode把PHP数组转换成json。

我的问题:函数nestify (来自第二个链接)给我的并不完全是我需要的。我需要这样的东西:http://pastebin.com/m68752352

你能帮我修改函数"nestify“,让它给我正确的数组吗?

下面是这个函数的最后一次:

代码语言:javascript
复制
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;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-05-20 09:00:01

下面这段代码可以解决这个问题,改编自我在网上找到的一些PHP Doctrine代码:

代码语言:javascript
复制
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;
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/841014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档