2012-02-15 47 views
5

說我有PHP中的數組,看起來像這樣:訪問價值

$values = Array(
     '0' => 'value1', 
     '1' => 'value2', 
     '2' => 'value3' 
    ) 

我想用小鬍子通過數組進行迭代,但我想關聯的值。這就是我希望做的事:

{{#values}} 
     {{the current value}} 
    {{/values}} 

我希望有返回的結果將是:

value1 
    value2 
    value3 

我已經得到解決此通過改變我的結構:

$values = Array(
     '0' => array('value=' =>'value1'), 
     '0' => array('value=' =>'value2'), 
     '0' => array('value=' =>'value3'), 
    ) 

和呼叫{{valule}}鬍子iterator中。

我應該做這樣一個完全不同的方式?我使用PHP中的SplFixedArray,我想用這個方法通過值迭代...

謝謝!

回答

9

隱含的Iterator是去簡單數據的方式。如果你的數據是比較複雜的,然後PHP的ArrayIterator做的工作做好。

這裏是我工作的一個例子。希望它對其他人有用。

$simple_data = array('value1','value2','value3'); 
$complex_data = array(array('id'=>'1','name'=>'Jane'),array('id'=>'2','name'=>'Fred')); 

$template_data['simple'] = $simple_data; 
$template_data['complex'] = new ArrayIterator($complex_data); 

$mustache->render('template_name', $template_data); 

而且在模板你可以有

{{#simple}} 
     {{.}}<br /> 
{{/simple}} 

{{#complex}} 
    <p>{{ id }} <strong>{{ name }}</strong></p> 
{{/complex}}