如何在 Twig 中按列名分组?

How to group by column name in Twig?

我正在尝试使用 Twig 在 for 循环中分组。我找到了 Twig 的扩展,它为 Twig 添加了额外的功能。这是 link: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

这是我的 twig 代码版本:

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

首先你的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 %}

你快到了。只需在语句外打印类别。

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

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