使用循环和计数使用Twig对数组值进行分组

时间:2015-07-28 04:21:38

标签: php twig

我有一系列需要组合在一起的数组。以下是传入数据的示例:

[pet_name] => Array
    (
        [0] => Bob
        [1] => Buster
    )

[type] => Array
    (
        [0] => cat
        [1] => dog
    )

[age] => Array
    (
        [0] => 1
        [1] => 22
    )

[gender] => Array
    (
        [0] => female
        [1] => male
    )

我正在尝试对这些进行分组以获得以下结果:

Pet #1
Name: Bob
Type: Cat
Age: 1
Gender: Female

Pet #2
Name: Buster
Type: Dog
Age: 22
Gender: Male

我尝试了以下方法但没有成功:

# Pet Info
{% set total = pet_name|length %}
{% set count = 0 %}

{% for count in total %}
# Pet #{{count + 1}}
* Name: {{ attribute(pet_name, count) }}
* Type: {{ attribute(type, count) }}
* Age: {{ attribute(age, count) }}
* Gender: {{ attribute(gender, count) }}
{% set count = count + 1 %}

{% endfor %}

第二种方法:

# Pet Info
{% set count = 0 %}

{% for pet in pet_name %}
# Pet #{{count}}
* Name: {{ attribute(pet_name, count) }}
* Type: {{ attribute(type, count) }}
* Age: {{ attribute(age, count) }}
* Gender: {{ attribute(gender, count) }}

{% set count = count + 1 %} 
{% endfor %}

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

{% for key, i in data['pet_name'] %}
  <ul>
      <li>Pet Num: {{ key + 1}}</li>
      <li>{{ data['pet_name'][key] }}</li>
      <li>{{ data['type'][key] }}</li>
      <li>{{ data['age'][key] }}</li>
      <li>{{ data['gender'][key] }}</li>
  </ul>
{% endfor %}

应该打印:

<ul>
    <li>Pet Num: 1</li>
    <li>Bob</li>
    <li>cat</li>
    <li>1</li>
    <li>female</li>
</ul>
<ul>
    <li>Pet Num: 2</li>
    <li>Buster</li>
    <li>dog</li>
    <li>22</li>
    <li>male</li>
</ul>

编辑:看来你有一个带数组的对象,在这种情况下尝试这样的事情:

{% for key, i in data.pet_name %}
  <ul>
      <li>Pet # {{ key + 1}}</li>
      <li>{{ data.pet_name[key] }}</li>
      <li>{{ data.type[key] }}</li>
      <li>{{ data.age[key] }}</li>
      <li>{{ data.gender[key] }}</li>
  </ul>
{% endfor %}
祝你好运!

答案 1 :(得分:1)

Angelcool让我走上正轨。这是最终的解决方案:

{% for key, i in pet_name %}
# #{{key + 1}}
* Name: {{ pet_name[key] }}
* Type: {{ type[key] }}
* Age: {{ age[key] }}
* Gender: {{ gender[key] }}

{% endfor %}

奇怪的是,这也开始起作用了:

# Pet Info
{% set count = 0 %}

{% for pet in pet_name %}
# Pet #{{count}}
* Name: {{ attribute(pet_name, count) }}
* Type: {{ attribute(type, count) }}
* Age: {{ attribute(age, count) }}
* Gender: {{ attribute(gender, count) }}

{% set count = count + 1 %}

{% endfor %}