2010-05-07 10 views
1

我更新我的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. 

問題是,我似乎只得到「字符串」在頁面上:(......):( 任何想法?

+1

我可以問你有什麼麻煩嗎? – webbiedave 2010-05-07 20:57:31

+0

哦!哈哈! 堅持:) – tarnfeld 2010-05-07 20:58:23

+0

更新:)那是怎麼回事? – tarnfeld 2010-05-07 21:00:00

回答

2
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個深度。

+0

謝謝!這應該做的伎倆! – tarnfeld 2010-05-07 21:08:48

+0

我很高興能幫上忙。 – TheClair 2010-05-07 21:29:25