如何在Twig中按列名分组?

时间:2019-03-22 12:39:14

标签: php twig slim-3

我正在尝试使用Twig在for循环中分组。我发现了Twig的扩展,它为twig添加了其他功能。这是该链接:twig-lambda。当我尝试按skillcategory分组时,它显示两次而不是一次。

这是我得到的数据:

[
  {
    "0": {
      "skillid": 1,
      "skillname": "PHP",
      "skillcategory": "Programing Langugages",
      "skilllevel": 62
    },
    "4": {
      "skillid": 5,
      "skillname": "C#",
      "skillcategory": "Programing Langugages",
      "skilllevel": 50
    }
  },
  {
    "1": {
      "skillid": 2,
      "skillname": "Walking",
      "skillcategory": "Others",
      "skilllevel": 20
    },
    "2": {
      "skillid": 3,
      "skillname": "Jumping",
      "skillcategory": "Others",
      "skilllevel": 100
    },
    "3": {
      "skillid": 4,
      "skillname": "Naping",
      "skillcategory": "Others",
      "skilllevel": 80
    }
  }
]

我真正想要得到的东西

Programing Langugages
PHP, C#

Others
Walking, Jumping, Naping

这是我的树枝代码版本:

{% for key, i in skills|group_by(=> _.skillcategory) %}
   {% for b in i %}
       <div>{{b.skillcategory}}</div>
       {{b.skillname}}
   {% endfor %}
{% endfor %}

2 个答案:

答案 0 :(得分:0)

首先您的JSON无效!

尝试一下:

[
  {
    "0": {
      "skillid": 1,
      "skillname": "PHP",
      "skillcategory": "Programin Langugages",
      "skilllevel": 62
    },
    "4": {
      "skillid": 5,
      "skillname": "C#",
      "skillcategory": "Programin Langugages",
      "skilllevel": 50
    }
  },
  {
    "1": {
      "skillid": 2,
      "skillname": "Walking",
      "skillcategory": "Others",
      "skilllevel": 20
    },
    "2": {
      "skillid": 3,
      "skillname": "Jumping",
      "skillcategory": "Others",
      "skilllevel": 100
    },
    "3": {
      "skillid": 4,
      "skillname": "Naping",
      "skillcategory": "Others",
      "skilllevel": 80
    }
  }
]

字符串应用双引号引起来。

编辑: 我不确定,但可以尝试以下方法:

{% for key, i in ['Programin Langugages', 'Others']|group_by(=> _.skillcategory) %}
   {% for b in i %}
       <div>{{b.skillcategory}}</div>
       {{b.skillname}}
   {% endfor %}
{% endfor %}

答案 1 :(得分:0)

您快到了。只需在类别外打印语句即可。

{% for key, i in skills|group_by(=> _.skillcategory) %}
   {{ key }}

   {% for b in i %}
       {{ b.skillname }}
   {% endfor %}
{% endfor %}