如何使用递归函数构建多维数组并通过引用传递

时间:2018-02-21 20:12:29

标签: php arrays recursion multidimensional-array

我想以这种格式构建并返回一个数组:

[
    [
        'prefLabel' => 'foo',
        'subclasses' => [
            [
                'prefLabel' => 'bar',
                'subclasses' => [
                    [
                        'prefLabel' => 'tee',
                        'subclasses' => [
                            [
                                //.. more of the same
                            ]
                        ]
                    ],
                    [
                        // ...
                    ]
                ]
            ],
            [
                'prefLabel' => 'baz',
                'subclasses' => [
                    [
                        // ...
                    ],
                    [
                        // ...
                    ]
                ]
            ],
        ]
    ],
]

深度未知。

我意识到这需要一个递归函数,但我这样做的方式总是返回一个维度,尽管有正确的子类:

public function search($keyword)
{
    $resp = $this->searchPrefLabels($keyword);

    foreach($resp->prefLabels as $obj) {
        $return[] = [
            'prefLabel' => $obj->prefLabel,
            'subclasses' => $this->getSubclasses($obj->prefLabel)
        ];
    }

    return $return;
}

// the recursive function
protected function getSubclasses($searchTerm, &$tree_string = []) 
{

    $resp = $this->searchSubClass($searchTerm);
    $tree = [];
    foreach($resp->subclasses as $subclass) {
        $tree[] = [
            'prefLabel' => $subclass->prefLabel
        ];
    }
    if(count($tree)) {
        $tree_string = array_merge($tree_string, $tree);
    }

    foreach($tree as $key => $val) {
        $val['subclasses'] = $this->getSubclasses($val['prefLabel'], $tree_string); 
    }

    return $tree_string;
}

以上内容返回类似于以下内容的内容:

[
    [
        'prefLabel' => 'foo',
        'subclasses' => [
            [
                'prefLabel' => 'bar',
            ],
            [
                'prefLabel' => 'baz',
            ],
            [
                'prefLabel' => 'tee',
            ],
            // ...
    ],
]

我希望它以上面显示的嵌套格式返回。

1 个答案:

答案 0 :(得分:1)

我认为你只需要一个函数用于递归(因为顶级看起来像所有子级别):

public function getPreLabelsAndSubClasses($keyword) {
    $result = [];
    $labels = $this->searchPrefLabels($keyword);
    foreach ($labels as $label) {
        $result[] = [
            'prefLabel' => $label,
            'subclasses' => $this->getPreLabelsAndSubClasses($label),
        ];
    }
    return $result;
}