Tree behavior - best practice for getting a proper resultset?

I want to use tree behavior for a comment function.
Each comment can also have a comment, which can also have a comment.
(Maximum depth is 4).
I wrote a function that recursively iterates through the comments and stores them in an array.

As far as I can see, this works, but I’m wondering: Isn’t there already a CakePHP solution for this?

    public function display($recipeId = null)
    {

        function iterate($inputs) {
            global $arr;
            foreach($inputs AS $input) {
                $arr[]=$input; /**** can these be replaced with echo $this->element('recipecomment') ?? */
                //echo $this->element('recipeComment',['recipeComment'=>$input]); /* ==> throws error 
                //Could not render cell - Using $this when not in object context [/var/www/html/alltime_recipes/src/View/Cell/RecipeCommentsCell.php, line 60]
                if ($input->hasValue('children')){
                    iterate($input->children);
                }
            }
            return($arr);
        }

        $recipecomments = $this->fetchTable('Recipecomments')
            ->find('threaded')
            //->select(['id','recipe_id','user_id','comment','recipecommentstate_id','level','created'])
            ->where(['Recipecomments.recipe_id'=>$recipeId])
            ->order(['Recipecomments.parent_id'=>'ASC','Recipecomments.lft'=>'ASC','Recipecomments.created'=>'DESC'])
            ->contain(['Users'=> [
                'fields'=>['Users.name','Users.id','Users.slug'],
                'Userprofiles'=>['fields'=>['picture']]
            ]]);
        //debug($recipecomments->toArray());
        $recipecomments= iterate($recipecomments);

        $this->set('recipecomments', $recipecomments);
    }