pil*_*guy 6 php arrays templates mustache
假设我在PHP中有一个看起来像这样的数组:
$values = Array(
'0' => 'value1',
'1' => 'value2',
'2' => 'value3'
)
Run Code Online (Sandbox Code Playgroud)
我想使用Mustache迭代数组,但我想要关联的值.这是我希望做的:
{{#values}}
{{the current value}}
{{/values}}
Run Code Online (Sandbox Code Playgroud)
我希望返回的结果是:
value1
value2
value3
Run Code Online (Sandbox Code Playgroud)
我通过将我的结构更改为:
$values = Array(
'0' => array('value=' =>'value1'),
'0' => array('value=' =>'value2'),
'0' => array('value=' =>'value3'),
)
Run Code Online (Sandbox Code Playgroud)
并在Mustache迭代器中调用{{valule}}.
我应该以完全不同的方式做这件事吗?我在PHP中使用SplFixedArray,我想使用此方法迭代值...
谢谢!
小智 11
隐式迭代器是获取简单数据的方法.如果您的数据更复杂,那么PHPs 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 );
Run Code Online (Sandbox Code Playgroud)
在你可以拥有的模板中
{{#simple}}
{{.}}<br />
{{/simple}}
{{#complex}}
<p>{{ id }} <strong>{{ name }}</strong></p>
{{/complex}}
Run Code Online (Sandbox Code Playgroud)
您可以使用小胡子的隐式迭代器功能:
https://github.com/bobthecow/mustache.php/tree/master/examples/implicit_iterator
{{#values}}
{{.}}
{{/values}}
Run Code Online (Sandbox Code Playgroud)
您的原始数组可能需要数字键,现在是字符串.它可能会那样工作,但我还没有测试过.