Noob17
Noob17

Reputation: 719

How would I loop through this associative array in twig?

I'm really have trouble trying loop this array in twig and have no clue how to get it done. I think it's a associative array and each loop has one key and an another array as value.

This is my array structure:

array(3) {
  ["kernteam"]=>
  array(2) {
    [0]=>
    object(TimberPost){
      ["id"]=>
      int(1) "1"
      ["Name"]=>
      string(4) "Jake"
      }
    }
    [1]=>
    object(TimberPost){
      ["id"]=>
      int(1) "2"
      ["Name"]=>
      string(4) "Paul"
      }
    }
  }
  ["partners"]=>
  array(2) {
    [0]=>
    object(TimberPost){
      ["id"]=>
      int(1) "3"
      ["Name"]=>
      string(4) "Cody"
      }
    }
  }
  ["trainers"]=>
  array(0) {
  }
}

And I would like to set the values of the arrays per loop to something like this:

<div class="{{array.name}}">
   <div class="person" id="{{object.id}}">
      <p>{{object.name}}</p>                
   </div>
 </div>

So my question is how to write this loop and call the key and values of the arrays inside it. Any help is appreciated thanks you!

Upvotes: 5

Views: 9164

Answers (1)

Steve
Steve

Reputation: 20459

{% for name, item in array %}
    <div class="{{name}}">
    {% for object in item %}
        <div class="person" id="{{object.id}}">
            <p>{{object.name}}</p>                
        </div>
    {% endfor %}
    </div>
{% endfor %}

Upvotes: 10

Related Questions