-1

I want to iterate through an array like this one:

array(
   ['aaa'] => ['a'],
   ['bbb'] => ['b']
)

Usually, I would do it this way:

{{#array}}{{array}}{{/array}} // 'a' 'b'

But - how can I display the current key in the loop above? I want to display something like 'aaa' 'a' 'bbb' 'b'. Is it possible?

user2124857
  • 39
  • 1
  • 1
  • 9

2 Answers2

0

It is not possible to iterate over an associative array in Mustache. It sees your associative array as a "context" rather than an iterable list.

You can make it iterable by preparing a View, or by pre-processing your data to make it into a more Mustache-friendly format. You could do this with a foreach loop before you pass the data into Mustache, but the easiest way to do this is probably by wrapping it in a Presenter. Try this one on for size:

https://gist.github.com/bobthecow/61161639d8be82a75b5e

bobthecow
  • 5,047
  • 25
  • 27
-2

Try this:

$a=array('aaa' => 'a', 'bbb' => 'b');
print_r($a);
foreach($a as $key => $val){
    echo $key . ' - ' . $val . '<br>';
}

Output

Array
(
    [aaa] => a
    [bbb] => b
)
aaa - a
bbb - b
Vineet1982
  • 7,730
  • 4
  • 32
  • 67