1

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.

1
  • try it but it is initialse $html evrytime Commented Jun 19, 2015 at 22:48

2 Answers 2

2

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']);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.