10

A var_dump for my array $strs[$key][$id] gives the following result:

array(2) {
    [0]=> array(4) {
        [8259]=> string(8260) "ouvrir 1"
        [8260]=> string(8261) "fichier 2"
        [8261]=> string(8262) "quitter 1"
        [8262]=> string(8263) "lire 2"
    }
    [1]=> array(4) {
        [8259]=> string(8260) "lancer 2"
        [8260]=> string(8261) "dossier 1"
        [8261]=> string(8262) "exit 1"
        [8262]=> string(8263) "lire 2"
    }
}

In my view, I'm tying to get all the strings with the same $id from all the $key. Something like this:
1-
ouvrir 1
lancer 2
2-
fichier 2
lancer 2

etc

I've tried this in my twig view:

{% for key,val in strs['key']['id']  %}
    {% if strs['key']['id'] is defined %}
     {{ key }} - <br/>      
     {{ val }}       
    {% endif %}   
{% endfor %}

I got this error:
Key "key" for array with keys "0, 1" does not exist in...
What Am I doing wrong here? And how can I get the result I'm looking for?

prehfeldt
  • 2,184
  • 2
  • 28
  • 48
Wissem
  • 1,705
  • 4
  • 16
  • 22

1 Answers1

11

Don't put this logic in your views. Use your views only to display stuff.
Do it in your controller instead and pass the result to your view:

$result = array();
foreach ($arrays as $array) {
  foreach ($array as $key => $value) {
    $result[$key][] = $value;
  }
}

The result will be an array whose keys will be the IDs, the values arrays of strings that belong to the same ID.

To display it:

{% for id, stringsById in results %}
  {{ id }}- <br />
  {% for string in stringsById %}
    {{ string }} <br />
  {% endfor %}
{% endfor %}
Samy Dindane
  • 17,900
  • 3
  • 40
  • 50
  • That's exactly what I have in my controller to get the $result array in the first place. I'm trying here to display the content of the array in my view. – Wissem May 23 '12 at 12:01
  • 2
    I updated my answer with the code for displaying the array's content. – Samy Dindane May 23 '12 at 12:28
  • Yes, that's the array's whole content. But, I'm trying to get for each $key its corresponding strs[id]. As in the example in my question: [8259]=> string(8260) "ouvrir 1" and [8259]=> string(8260) "lancer 2" share the same id(8259) but for a different key (0 and 1). Now what I want is to group and show these two on each loop. – Wissem May 23 '12 at 18:06