【问题标题】:Looping class, for template engine kind of thing循环类,用于模板引擎之类的东西
【发布时间】:2010-05-07 20:55:38
【问题描述】:

我正在更新我的课程Nesty,所以它是无限的,但我遇到了一点麻烦......这是课程:

<?php

Class Nesty
{

    // Class Variables
    private $text;
    private $data = array();
    private $loops = 0;
    private $maxLoops = 0;

    public function __construct($text,$data = array(),$maxLoops = 5)
    {
        // Set the class vars
        $this->text = $text;
        $this->data = $data;
        $this->maxLoops = $maxLoops;

    }

    // Loop function
    private function loopThrough($data)
    {

        if( ($this->loops +1) > $this->maxLoops )
        {
            die("ERROR: Too many loops!");
        }
        else
        {
            $keys = array_keys($data);

            for($x = 0; $x < count($keys); $x++)
            {
                if(is_array($data[$keys[$x]]))
                {
                    $this->loopThrough($data[$keys[$x]]);
                }
                else
                {
                    return $data[$keys[$x]];
                }
            }
        }

    }

    // Templater method
    public function template()
    {
        echo $this->loopThrough($this->data);
    }

}

?>

以下是您将用于创建类实例的代码:

<?php

// The nested array
$data = array(
    "person" => array(
        "name" => "Tom Arnfeld",
        "age" => 15
    ),
    "product" => array (
        "name" => "Cakes",
        "price" => array (
            "single" => 59,
            "double" => 99
        )
    ),
    "other" => "string"
);  

// Retreive the template text
$file = "TestData.tpl";
$fp = fopen($file,"r");
$text = fread($fp,filesize($file));

// Create the Nesty object
require_once('Nesty.php');
$nesty = new Nesty($text,$data);

// Save the newly templated text to a variable $message
$message = $nesty->template();

// Print out $message on the page
echo("<pre>".$message."</pre>");

?>

这是一个示例模板文件:

Dear <!--[person][name]-->,

Thanks for contacting us regarding our <!--[product][name]-->. We will try and get back to you within the next 24 hours.

Please could you reply to this email to certify you will be charged $<!--[product][price][single]--> for the product.

Thanks,
Company.

问题是我似乎只在页面上显示“字符串”... :( 有什么想法吗?

【问题讨论】:

  • 请问您遇到的问题是什么?
  • 嗯?除了 str_replace 或常规 PHP 语法对于这种简单的情况更容易之外,您在类中的哪里进行实际的字符串替换?

标签: php class arrays


【解决方案1】:
if(is_array($data[$keys[$x]]))
{
   $this->loopThrough($data[$keys[$x]]);
}
else
{
   return $data[$keys[$x]];
}

你需要从第一个 if 语句返回。

if(is_array($data[$keys[$x]]))
{
   return $this->loopThrough($data[$keys[$x]]);
}
else
{
   return $data[$keys[$x]];
}

这将在您递归时返回结果。您现在只能获得“字符串”,因为该键在您的数组结构中只有 1 级。

【讨论】:

    猜你喜欢
    • 2012-06-06
    • 1970-01-01
    • 2019-12-19
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多