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?

1 Answer 1

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 %}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I updated my answer with the code for displaying the array's content.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.