Laravel 递归映射

问题描述 投票:0回答:2

我需要在 Laravel 中实现一个递归映射函数。我的数据看起来像这样。

如果 all_children 为空,那么我将停止调用递归...

我的代码看起来像这样,但它不起作用......

public function mapRecursive($model){

    return collect($model)->map(function($val, $key){
        if($key == 'accessables'){
            return $val->accessables;
        }
        if($key == 'all_children'){
            if (count($val->allChildren > 1)){
                $this->mapRecursive($val->allChildren);
            }
        }
    });


}

我真的不知道该怎么做...如果您有想法,我们将不胜感激。

php laravel recursion
2个回答
1
投票

感谢您的宝贵时间...这是我的简单解决方案。

public function mapRecursive($array) {
        $result = [];
        foreach ($array as $item) {
            $result[] = $item['accessables'];
            $result = array_merge($result, $this->mapRecursive($item['allChildren']));
        }
        return array_filter($result);
    }

并且它有效...


0
投票

你尝试过这个吗?

if (!(isset($val->allChildren)))
{
  break;
}
© www.soinside.com 2019 - 2024. All rights reserved.