2012-02-15 75 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}}