【问题标题】:html as php variable not rendered properlyhtml 作为 php 变量未正确呈现
【发布时间】: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-&gt;printDropdownTree($t['_children']....
  • 是的,你是对的,谢谢。你能把答案贴出来吗?我愿意接受吗

标签: php html var


【解决方案1】:

简单的解决方案:你必须获取函数递归调用的结果!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多