【发布时间】:2014-02-12 12:11:46
【问题描述】:
有以下方法
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 不会被渲染
【问题讨论】:
-
我认为
return必须超出 foreach 循环。此外,您可以将printf替换为sprintf。 -
哦,是的,抱歉,发布时出现拼写错误。
-
另外你不获取这个函数的递归调用的返回值,你必须这样做
$html .= $this->printDropdownTree($t['_children']....。 -
是的,你是对的,谢谢。你能把答案贴出来吗?我愿意接受吗