Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Mustache. Implicit iterator: How to get key of current value(numeric php array)

If I have php array like this:

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

And keys present important information - It can be some constant values, ids e.t.c

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!

like image 819
Magix- Avatar asked Mar 25 '13 11:03

Magix-


People also ask

How to get a specific value from an array in PHP?

PHP array is a collection of items that are stored under keys. There are two possible types of keys: strings and integers. For any type of key, there is a common syntax to get a specific value by key — square brackets. Example 2: Sometimes we can accidentally try to get a non-existent item from the array. In this case, PHP throws a NOTICE.

How to iterate through an associative array in PHP?

It requires counting the size of the array and store in a variable for iteration. This is required to iterate through the elements of an associative array. After that, you also have to return the array keys using the PHP array_keys () to find the keys using the loop.

How to get the key of an array in PHP?

Well, PHP has a function which can get the key for a given value of an array. If same value is in the array for multiple times then it will return the first key. How To Read A Text File Line By Line In PHP?

How to find first key of associative array in PHP?

Find First Key of Associative Array with PHP Foreach Loop. To find the first key from an associative array, you can use the PHP foreach loop. The loop takes an argument as the associative array variable and the $key => $value to get the items of the array in PHP. It traverses through all the elements of the array.


2 Answers

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.

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);
    }
}

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 }}
like image 125
bobthecow Avatar answered Sep 19 '22 17:09

bobthecow


I love mustache. While learning I found this question and felt it needed an appropriate answer.

$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);

Then you can use it in your template like so:

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

This can be expanded much further than Key/Val by adding more values in the foreach loop.

like image 31
Bill Effin Murray Avatar answered Sep 21 '22 17:09

Bill Effin Murray