PHP胡子.隐式迭代器:如何获取当前值的键(数字php数组) [英] PHP Mustache. Implicit iterator: How to get key of current value(numeric php array)
问题描述
如果我有这样的php数组:
If I have php array like this:
$a = array (
99 => 'Something1',
184 => 'Something2',
);
并且键显示重要信息-它可以是一些常量值,例如ids
And keys present important information - It can be some constant values, ids e.t.c
然后如何从Templete获取当前元素的密钥. 例如:
Then how can I get key of current element from templete. For example:
{{#data}}
{.} - it is current value, but I need key also.
{{/data}}
在我们的系统中,这类数组太多了,因此以前很难重新解析它们.有什么更好的解决方案? 非常感谢你!
In our system too much these kind of arrays and it is uncomfortably re-parse them before. What's better solution for this? Thank you very much!
推荐答案
不可能在Mustache中的关联数组上进行迭代,因为Mustache将其视为哈希"而不是可迭代的列表.即使您可以遍历列表,也将无法访问密钥.
It is not possible to iterate over an associative array in Mustache, because Mustache sees it as a "hash" rather than an iterable list. And even if you could iterate over the list, you would not be able to access the keys.
为此,您必须准备数据.您可以在将数据传递到Mustache之前使用foreach循环来完成此操作,也可以通过将数组包装在"Presenter"中来进行操作.这样的事情应该可以解决问题:
In order to do this, you must prepare your data. You could do it with a foreach loop before you pass the data into Mustache, or you could do it by wrapping your array in a "Presenter". Something like this ought to do the trick:
<?php
class IteratorPresenter implements IteratorAggregate
{
private $values;
public function __construct($values)
{
if (!is_array($values) && !$values instanceof Traversable) {
throw new InvalidArgumentException('IteratorPresenter requires an array or Traversable object');
}
$this->values = $values;
}
public function getIterator()
{
$values = array();
foreach ($this->values as $key => $val) {
$values[$key] = array(
'key' => $key,
'value' => $val,
'first' => false,
'last' => false,
);
}
$keys = array_keys($values);
if (!empty($keys)) {
$values[reset($keys)]['first'] = true;
$values[end($keys)]['last'] = true;
}
return new ArrayIterator($values);
}
}
然后只需将您的数组包装在Presenter中:
Then simply wrap your array in the Presenter:
$view['data'] = new IteratorPresenter($view['data']);
您现在可以在遍历数据时访问键和值:
You now have access to the keys and values while iterating over your data:
{{# data }}
{{ key }}: {{ value }}
{{/ data }}
这篇关于PHP胡子.隐式迭代器:如何获取当前值的键(数字php数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!