Laravel递归地图

时间:2019-06-25 06:53:06

标签: laravel

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

enter image description here

如果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);
            }
        }
    });


}

我真的不知道该怎么做。。。

2 个答案:

答案 0 :(得分: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);
    }

它有效...

答案 1 :(得分:0)

您尝试过吗?

if (!(isset($val->allChildren)))
{
  break;
}