phparraystwigsilex

Filtering and splicing an array in Twig


I have an array of user records (0 indexed, from a database query), each of which contains an array of fields (indexed by field name). For example:

Array
(
    [0] => Array
        (
            [name] => Fred
            [age] => 42
        )

    [1] => Array
        (
            [name] => Alice
            [age] => 42
        )

    [2] => Array
        (
            [name] => Eve
            [age] => 24
        )

)

In my Twig template, I want to get all the users where the age field is 42 and then return the name field of those users as an array. I can then pass that array to join(<br>) to print one name per line.

For example, if the age was 42 I would expect Twig to output:

Fred<br>
Alice

Is this possible to do in Twig out of the box, or would I need to write a custom filter? I'm not sure how to describe what I want in a couple of words so it may be that someone else has written a filter but I can't find it by searching.


Solution

  • Final solution was a mix of what has been posted so far, with a couple of changes. The pseudocode is:

    for each user
      create empty array of matches
      if current user matches criteria then
        add user to matches array
    join array of matches
    

    Twig code:

    {% set matched_users = [] %}
      {% for user in users %}
        {% if user.age == 42 %}
          {% set matched_users = matched_users|merge([user.name|e]) %}
        {% endif %}
      {% endfor %}
      {{ matched_users|join('<br>')|raw }}
    

    merge will only accept an array or Traversable as the argument so you have to convert the user.name string to a single-element array by enclosing it in []. You also need to escape user.name and use raw, otherwise <br> will be converted into &lt;br&gt; (in this case I want the user's name escaped because it comes from an untrusted source, whereas the line break is a string I've specified).