2014-01-22 87 views
1

具有以下方法HTML作爲PHP變量不能正確渲染

public function printDropdownTree($tree, $r = 0, $p = null) { 
     foreach ($tree as $i => $t) { 
      $dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) . ' '; 
      printf("\t<option value='%d'>%s%s</option>\n", $t['id'], $dash, $t['name']); 
      if ($t['parent'] == $p) { 
       // reset $r 
       $r = 0; 
      } 
      if (isset($t['_children'])) { 
       $this->printDropdownTree($t['_children'], ++$r, $t['parent']); 
      } 
     } 
    } 

打印出嵌套的選擇選項和工作正常。但我想返回結果爲變量,我試圖做到這一點像

public function printDropdownTree($tree, $r = 0, $p = null) { 
     $html = ""; 
     foreach ($tree as $i => $t) { 
      $dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) . ' '; 
      $html .= '<option value="'.$t['id'].'">'.$dash.''.$t['name'].'</option>'; 
      if ($t['parent'] == $p) { 
       // reset $r 
       $r = 0; 
      } 
      if (isset($t['_children'])) { 
       $this->printDropdownTree($t['_children'], ++$r, $t['parent']); 
      } 
     } 


     return $html; 
    } 

$dash不會得到渲染

+1

我認爲'return'必須超出foreach循環。另外,你可以用'sprintf'代替'printf'。 –

+0

哦耶對不起在張貼錯字錯誤。 – fefe

+0

另外你也沒有獲取這個函數的遞歸調用的返回值,你必須做'$ html。= $ this-> printDropdownTree($ t ['_ children'] ....'。 –

回答

0

簡單的解決辦法:你要取遞歸的結果功能的調用!

public function printDropdownTree($tree, $r = 0, $p = null) { 
    $html = ""; 
    foreach ($tree as $i => $t) { 
     $dash = ($t['parent'] == 0) ? '' : str_repeat('-', $r) . ' '; 
     $html .= '<option value="'.$t['id'].'">'.$dash.''.$t['name'].'</option>'; 
     if ($t['parent'] == $p) { 
      // reset $r 
      $r = 0; 
     } 
     if (isset($t['_children'])) { 
      $html .= $this->printDropdownTree($t['_children'], ++$r, $t['parent']); 
     } 
    } 


    return $html; 
}