模板类不使用str_replace循环

时间:2011-10-10 06:48:41

标签: php foreach while-loop str-replace

我有这套代码

<?php
include "includes/config.php";
class template{
    var $page;
    var $built;
    public $block = array();

    function _start($tpl){
        $this->page = $tpl;
    }

    function set_array($data){
        $this->block[] = $data;
    }

    function _show(){
        foreach($this->block as $k => $v){
            foreach($v as $k1 => $v1){
                //echo $k1."<br />";
                //echo $v1."<br />";
                $this->page = str_replace("{".$k1."}", $v1, $this->page);
            }
        }
        echo $this->page;
    }
}

$template = new template();

$file = "<html>
<body>
<p>{CAT}</p>
<p>{SUBCAT}</p>
</body>
</html>";

$template->_start($file);

// Category Query
while($row1 = mysql_fetch_assoc($cat)){

$template->set_array(array("CAT" => $row1['title']));

// Sub Category Query
while($row2 = mysql_fetch_assoc($subcat)){

$template->set_array(array("SUBCAT" => $row2['title']));

}
}

$template->_show();

?>

现在,当我回显$ k1或$ v1时,它们会以正确的顺序显示键和值,如

CAT1 SUBCAT1.1 SUBCAT1.2 CAT2 SUBCAT2.1 SUBCAT2.2

但是当它通过str_replace时它只显示CAT1和SUBCAT1.2出了什么问题?

1 个答案:

答案 0 :(得分:0)

你正在覆盖foreach()循环中的变量$ page;要么使它成为数组,要么附加到变量。可能是:

function _show(){
       $this->page = '';
        foreach($this->block as $k => $v){
            foreach($v as $k1 => $v1){
                $this->page .= str_replace("{".$k1."}", $v1, $this->page); //appending every time onto the previous. As you were doing:
                // $this->page =str_replace("{".$k1."}", $v1, $this->page);
                // here you were overwriting $this->page at every passage of the loop
            }
        }
        echo $this->page;
    }