简体   繁体   中英

Looping with twig

How do I do this with twig?

    foreach($estimate_data AS $year => $month) {
        foreach ($month AS $monthNo => $estimates) {
          $chart_data .= "['". $year ."/".$monthNo."',"; 
          foreach (array(0, 1, 3, 5, 8, 13, 20) AS $est){
              $chart_data .= (isset($estimates[$est]) ? $estimates[$est] : 0) .",";
          }
          $chart_data .= "],\n";
        }
    }

This is what I have so far, but I'm struggling with the inner foreach and checking the existence of an element in the array:

      {% for year, month in chart_data %}
        {% for month_no, estimates in month %}
          ['{{year}}/{{month_no}}',
          {% for i in [0, 1, 2, 3, 5, 8, 13, 20]  %}
            {% if estimates %}
            {{estimates[i]}} ,
            {% endif %}
          {% endfor %}
        {% endfor %}
      {% endfor %}

Try this..

Untested!!..

{% for year, month in estimate_data %}
    {% for month_no, estimates in month %}
        {% set chart_data = chart_data ~ "['" ~ year ~ "/" ~ monthNo ~ "'," %} # concat the strings
        {% for est in [0, 1, 3, 5, 8, 13, 20] %}
            {% set chart_data = chart_data ~ (defined estimates.est) ? estimates.est : 0 ~ ',' %} # if estimates.est is defined
        {% endfor %}
        {% set chart_data = chart_data ~ "],\n" %} # concat the final string.
    {% endfor %}
{% endfor %}

EDIT: I guess, if you try to concat using:

{% set variable ~= 'text' %}

This should work, but I don't even test this..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM