Search code examples
phpmustache

Mustache Template for nested array


How can I loop through this using mustache? I have an outer array of numeric indexes. Or how to do something else and keep this structure?

I tried:

<ul>
{{#cars}}  
<li> {{#.}} {{.}} {{/.}}</li>
{{/cars}}
</ul>

Array

>   Array(
>             [cars] => Array 
>                 (
>                  [0] => Array
>                      (
>                        [0] => Array
>                           (
>                             [id] => 343443
>                             [name] => Mazda
>                           )
>         
>                         [1] =>
>                           (
>                             [id] => 45353
>                             [name] => Toyota
>                           )
>                      )
>                   [1] => Array 
>                       (
>                          [0] => Array 
>                           (
>                             [id] => 922424
>                             [name] => Camry
>                           )
>                        )
>                   )//end cars
>         )

Solution

  • Try this template:

    <ul>
        {{#cars}}
            {{#.}}
            <li>{{id}} - {{name}}</li>
            {{/.}}      
        {{/cars}}
    </ul>
    

    Or convert the array:

    array_walk( $array['cars'], function($i) use (&$cars) {
        foreach( $i as $v ) $cars['cars'][] = $v;       
    });
    

    , and use this simpler template:

    <ul>
        {{#cars}}
            <li>{{id}} - {{name}}</li>  
        {{/cars}}
    </ul>