2015-06-19 122 views
1

我试图在控制器而不是js中创建html。 有一个数组深度未知的数组。循环里面的递归函数

$tree = $repo->childrenHierarchy(); 

和一个函数,它读取数组并从数组元素中返回一个html字符串。

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

我的问题是,我不能保持总字符串,因为每次的函数调用自身的变种HTML被初始化,需持串像全球,但不能图如何。

+0

尝试,但它是initialse $ HTML evrytime –

回答

0

不应该有任何错误,只需将该值存储在类属性中,而操作?

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

是完蛋了感谢 –

2

看这多一点之后,我不认为这真的看起来像在$html在递归调用初始化的问题。在我看来,它实际上应该开始为孩子们空着。但它看起来不像你将孩子追加到你已经去过的$html字符串。我认为你需要

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

是不是

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

你对这个工作也日Thnx –