获取twig中的数组索引#

Bre*_*son 6 php twig

试图在twig中输出数组的索引#,在文档中找不到它.有谁知道如何得到它?

array(2) {
  [0]=>
  array(2) {
    ["testimonial"]=>
    string(18) "Derby Heist Test 1"
    ["author"]=>
    string(6) "test 1"
  }
  [1]=>
  array(2) {
    ["testimonial"]=>
    string(18) "Derby Heist Test 2"
    ["author"]=>
    string(6) "test 2"
  }
}
Run Code Online (Sandbox Code Playgroud)

所以我想在for循环中输出索引号0和1.请帮忙.

Mat*_*teo 9

您可以使用循环变量作为示例:

{% for user in users %}
    {{ loop.index }} - {{ user.username }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

loop.index循环的当前迭代.(1索引)

loop.index0循环的当前迭代.(0索引)

希望这有帮助


Stu*_*art 5

只需 foreach 遍历您的主数组,并指定您想要的索引:

foreach($array as $index=>$arr) { ...
Run Code Online (Sandbox Code Playgroud)

$index 现在将为您提供您需要的内容。

或者通过树枝:

{% for key,value in array_path %}
    Key : {{ key }}
    Value : {{ value }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。虽然 Matteos 版本在大多数情况下都可以工作,但对于有孔的阵列,它不会给出正确的结果。 (2认同)