Rbex
Rbex

Reputation: 1539

Laravel Recursive Map

I need to implement a recursive map function in Laravel. My data looks like this.

enter image description here

If all_children is empty then I will stop calling the recursive...

My code looks like this, but it doesn't work...

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


}

I don't really know how to do it... If you have idea your help is appreciated.

Upvotes: 1

Views: 1310

Answers (2)

Rbex
Rbex

Reputation: 1539

Thank you for your time...Here is my simple solution.

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

and it works...

Upvotes: 1

Josep Feixas
Josep Feixas

Reputation: 51

have you tried this?

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

Upvotes: 0

Related Questions