0

I have a problem, in Controller I have a multidimensional array, but I don't know how many dimensional this array is. It is dynamically and determined by database, so can I put it to twig in any way?

When I'm using function dump in twig, it displays:

array(5) { 
  [0]=> int(50) 
  [1]=> int(51) 
  [2]=> int(52) 
  [51]=> array(2) { 
    [0]=> int(55) 
    [55]=> array(1) { 
      [0]=> int(56) 
    } 
  } 
  [52]=> array(2) { 
    [0]=> int(53) 
    [1]=> int(54) 
  } 
} 
Wilq
  • 2,245
  • 4
  • 33
  • 37
kgruszowski
  • 76
  • 2
  • 9

1 Answers1

4

Okay, you can do that like this: (if you know your array has only one more dimension, total 2 dimensions).

{% for key, item in items %}
    {% if item is iterable %}
        {% for sub_item in item %}
            Do something...
        {% endfor %}
    {% else %}
        Do something else...
    {% endif %}
{% endfor %}

If you have a multidimensional array that has more than 1 sub array, you have to call a function recursively to reach that other sub dimensions. You can do it in your twig extension file.

A recursive function is calling itself to reach sub items in a multidimensional array. I don't know what do you want to do with that array but i'm gonna make a basic function depends on your array.

function recursiveTwig($array)
{
    foreach($array as $key => $value){
        if(is_array($key)) {
            $this->recursiveTwig($key);
        } else {
            //Do something with your value...
        }
    }
}

Macro:

How to render a tree in Twig

Community
  • 1
  • 1
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
  • Nope. you can use it in your twig_extension file. http://symfony.com/doc/current/cookbook/templating/twig_extension.html but if you want to do it with macros, you can set a macro in a twig file and include it. – Canser Yanbakan May 19 '14 at 13:29
  • thank you very much, it works :) I use macro, I think it's a better way – kgruszowski May 19 '14 at 13:32