php 用 Twig 创建一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43094837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an array with Twig
提问by Hyman Brummer
I have this in PHP:
我在 PHP 中有这个:
$units = array();
foreach ($popPorts as $port) {
$units[$port->getFrameNo()][$port->getSlotNo()][$port->getPortNo()] = $port->getPortNo();
}
How can I achieve the same in twig?
我怎样才能在树枝上实现同样的目标?
I have tried this so far:
到目前为止我已经尝试过这个:
{% set frames = [] %}
{% for row in object.popPorts %}
{% set frames[row.frameNo][row.slotNo][row.portNo] = row.portNo %}
{% endfor %}
{{ dump(frames) }}
But then I get an error:
但后来我收到一个错误:
Unexpected token "punctuation" of value "[" ("end of statement block" expected).
值“[”的意外标记“标点符号”(预期“语句块结束”)。
The output should be like this:
输出应该是这样的:
array (size=3)
(frame) 1 =>
array (size=2)
(slot) 1 =>
array (size=4)
0 => (port) 26
1 => (port) 27
2 => (port) 28
3 => (port) 29
(slot) 5 =>
array (size=2)
0 => (port) 31
1 => (port) 34
(frame) 2 =>
array (size=1)
(slot) 3 =>
array (size=1)
0 => (port) 32
(frame) 3 =>
array (size=1)
(slot) 6 =>
array (size=1)
0 => (port) 33
回答by Javier Eguiluz
I'm afraid you can't create arrays like that in Twig. Even appending new items to an array is complicated because you need to create an array for the new element and concatenate it with the existing array. Example:
恐怕你不能在 Twig 中创建这样的数组。即使将新项添加到数组也很复杂,因为您需要为新元素创建一个数组并将其与现有数组连接起来。例子:
{% set array = [] %}
{% for item in items %}
{% set array = array|merge([{ title: item.title, ... }]) %}
{% endfor %}
I know this looks awful, but all this inconvenience is done on purpose. Twig is meant to create templates, so the features available to create or process information are limited on purpose. The idea is that heavy data processing should be done with PHP.
我知道这看起来很糟糕,但所有这些不便都是故意造成的。Twig 旨在创建模板,因此可用于创建或处理信息的功能是有目的的。这个想法是大量的数据处理应该用 PHP 来完成。
回答by Vincent Moulene
Another way :
其它的办法 :
{% set array = {
'item-1': {
'sub-item-1': 'my-sub-item-1',
'sub-item-2': 'my-sub-item-2',
},
'item-2': {
'sub-item-1': 'my-sub-item-1',
'sub-item-2': 'my-sub-item-2',
},
'item-3': {
'sub-item-1': 'my-sub-item-1',
'sub-item-2': 'my-sub-item-2',
}
}
%}