Giorgos Nikolaidhs
Giorgos Nikolaidhs

Reputation: 71

recursive function inside for loop

I m trying to create html in the controller instead of js. There is an array with unknown depth of arrays.

$tree = $repo->childrenHierarchy();

and a function who reads the array and returns a string of html with values from array elements.

 public function recursive($tree) {
        $html = "";
        foreach ($tree as $t) {
            $html = $html . '<li> <span><i class="fa fa-lg fa-minus-circle"></i>' . $t['title'] . '</span>';
            if ($t['__children'] != null) {
                $html = $html . '<ul>';
                $this->recursive($t['__children']);
                $html = $html . '</ul>';
            } else {
                $html = $html . '</li>';
            }
            return $html;
        }

My problem is that i cant hold the total string because everytime the function calls itself the var html is initialised, need to hold the string something like global but cant figure how.

Upvotes: 1

Views: 874

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41810

After looking at this a little more, I don't think it really looks like a problem that the $html is initialized in the recursive calls. It seems to me that it actually should start as empty for the children. But it doesn't look like you're appending the children to the $html string you already have going. I think you need

$this->recursive($t['__children']);

to be instead

$html .= $this->recursive($t['__children']);

Upvotes: 2

john Smith
john Smith

Reputation: 17906

there shouldnt be anything wrong with just storing that value in class property while action ?

public $html = "";

 public function recursive($tree) {
        foreach ($tree as $t) {
            $this->html = $this->html . '<li> <span><i class="fa fa-lg fa-minus-circle"></i>' . $t['title'] . '</span>';
            if ($t['__children'] != null) {
                $this->html = $this->html . '<ul>';
                $this->recursive($t['__children']);
                $this->html = $this->html . '</ul>';
            } else {
                $this->html = $this->html . '</li>';
            }
            return $this->html;
        }

Upvotes: 0

Related Questions