模板在一个数组中分配循环,但得到错误

时间:2013-06-08 07:39:46

标签: php javascript html

我试图仅在1个数组中循环所有赋值,但是我得到的错误如下图所示, 任何人都可以教我怎么做?为什么会出现这个错误?非常感谢

enter image description here

这是我的template.php     

class Template{
    private $vars = array();

    public function assign($key, $value){
        $this->vars[$key] = $value;
    }

    public function render($template_name){
        $path = $template_name. '.html';

        if(file_exists($path)){
            $contents = file_get_contents($path);

            foreach($this->vars as $key => $value){
                $contents = preg_replace('/\[' . $key . '\]/', $value, $contents);
            }
            $pattern = array(
                                '/\<\!\-\- if (.*) \-\-\>/',
                                '/\<\!\-\- else \-\-\>/',
                                '/\<\!\-\- endif \-\-\>/',
                                '/\<\!\-\- echo (.*) \-\-\>/'
                            );
            $replace = array(
                                '<?php if($1) : ?>',
                                '<?php else : ?>',
                                '<?php endif; ?>',
                                '<?php echo ($1) ?>'
                            );
            $contents = preg_replace($pattern, $replace, $contents);

            eval(' ?>' . $contents . '<?php ');
        }else {
            exit('<h1>Template error!</h1>');
        }
    }

}

?>

指定分配值,然后在我的html中可以只写[value]来显示它的值

的header.php

<?php

session_start();
header('Content-Type: text/html; charset=utf-8');
include $_SERVER['DOCUMENT_ROOT'] . '/class/template.php';

$game = '2';
$tech = '3';
$beauty = '4';
$bagua = '1';

$template = new Template;
$template->assign('sitename', 'site name');
$template->assign('title', '');

$code = array(
                'test1',
                'test2',
                'test3'
            );

$word = array(
                'haha1',
                'haha2',
                'haha3'
            );

$template->assign($code, $word);
$template->assign('test4', 'haha4');
$template->render('view/default/header');
?>

了header.html

[test1][test2][test3][test4]

结果: enter image description here

2 个答案:

答案 0 :(得分:0)

正如Damien指出的那样:你正试图将一个数组分配给另一个数组的键,这就是抛出错误。

这里一个很好的解决方案是调整assign方法来接受一个数组:

public function assign($key, $value = false)
{
    if (is_array($key))
    {
        foreach ($key as $k => $v) $this->vars[$k] = $v;
    }
    else
    {
        $this->vars[$key] = $value;
    }
}

现在你可以向assign方法发送数组或$ key,$ value,它将处理这两种情况。

当然,您可以将添加的键更改为字符串而不是数组:)

答案 1 :(得分:0)

已经有一个内置的PHP函数可以执行您想要的操作: array_combine

在您的示例代码中,您可以执行以下操作:

public function assign($key, $value){
    if(is_array($key)) {
        $this->vars = array_merge($this->vars, array_combine($key, $value));
    } else {
        $this->vars[$key] = $value;
    }
}

或使用for循环简单地实现类似的东西。