小编ver*_*rb8的帖子

使用父/子关系(PHP)重新构造n级数组

我想重组一个数组,并且有一些关于stuckoverflow的解决方案帮助我让它适用于第一级项目,但你会注意到数组是n级深度.

方法restructure()不是递归使用的(应该​​是).它可能完全是错误的,并且不知道如何使它正确.

儿童关键说,有孩子与各自的ID,家长关键环节的项目父ID.

class FilterMenu {

    protected $tree = array();

    static protected $structure = array();

    public function __construct(array $tree)
    {
        $this->tree = $tree;
    }

    public function getStructure()
    {
        self::restructure($this->tree);
        return self::$structure;
    }

    static public function restructure(array $structure)
    {
        foreach ($structure as $k => $v)
        {
            if (isset($v['parent']) and isset($v['children']) and count($v['children']) == 1)
            {
                // only 1 child
                self::$structure[$k] = current(array_keys($v['children']));
            }
            elseif (isset($v['children']))
            {
                $keys = array_keys($v['children']);
                self::$structure[$k] = array_combine($keys, $keys); // mirror …
Run Code Online (Sandbox Code Playgroud)

php multidimensional-array

5
推荐指数
1
解决办法
1027
查看次数

标签 统计

multidimensional-array ×1

php ×1