【问题标题】:PHP Mustache. Implicit iterator: How to get key of current value(numeric php array)PHP 小胡子。隐式迭代器:如何获取当前值的键(数字 php 数组)
【发布时间】:2013-03-25 11:34:52
【问题描述】:

如果我有这样的 php 数组:

 $a = array (
    99 => 'Something1',
    184 => 'Something2',
 );

而键表示重要信息 - 它可以是一些常量值,ids e.t.c

那么如何从模板中获取当前元素的键。 例如:

{{#data}}

{.} - it is current value, but I need key also.

{{/data}}

在我们的系统中,这类数组太多了,以前重新解析它们很不舒服。有什么更好的解决方案? 非常感谢!

【问题讨论】:

    标签: mustache mustache.php


    【解决方案1】:

    不可能在 Mustache 中迭代关联数组,因为 Mustache 将其视为“散列”而不是可迭代列表。即使您可以遍历列表,也无法访问密钥。

    为此,您必须准备好数据。在将数据传递到 Mustache 之前,您可以使用 foreach 循环来执行此操作,或者您可以通过将数组包装在“Presenter”中来执行此操作。这样的事情应该可以解决问题:

    <?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 中:

    $view['data'] = new IteratorPresenter($view['data']);
    

    您现在可以在迭代数据时访问键和值:

    {{# data }}
        {{ key }}: {{ value }}
    {{/ data }}
    

    【讨论】:

    • 非常感谢您的课程。我对它进行了测试,现在在稳定的实时环境中使用它。工作正常。
    【解决方案2】:

    我喜欢小胡子。在学习的过程中,我发现了这个问题,并认为它需要一个合适的答案。

    $this->keyValueArray = Array(
        "key1" => "val1",
        "key2" => "val2",
        "key3" => "val3"
    );
    
    $tempArray = array();
    foreach($this->keyValueArray as $key=>$val){
        $tempArray[] = Array("keyName" => $key, "valName" => $val);
    }
    
    $this->mustacheReadyData = ArrayIterator($tempArray);
    

    然后你可以像这样在你的模板中使用它:

    {{#mustacheReadyData}}
        Key: {{keyName}} Value: {{valName}}
    {{/mustacheReadyData}}
    

    通过在 foreach 循环中添加更多值,这可以比 Key/Val 进一步扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-04
      • 2013-05-27
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 2011-06-15
      • 2020-10-02
      • 2011-08-29
      相关资源
      最近更新 更多