[英]Get specific key from an array
Here is what I put in my Symfony session这是我在 Symfony 会话中的内容
$this->session->set('teams', [
'team_1' => ['MyTeamNameA' => ['player-1' => $safe['team-1-player-1'], 'player-2' => $safe['team-1-player-2'], 'player-3' => $safe['team-1-player-3'], 'player-4' => $safe['team-1-player-4'], 'points' => 0]],
'team_2' => ['MyTeamNameB' => ['player-1' => $safe['team-2-player-1'], 'player-2' => $safe['team-2-player-2'], 'player-3' => $safe['team-2-player-3'], 'player-4' => $safe['team-2-player-4'], 'points' => 0]],
]);
And now, in my Twig, I want to retrieve my team_1
's name, for example, I did this:现在,在我的 Twig 中,我想检索我的team_1
的名称,例如,我这样做了:
app.session.get('teams')['team_1']
It doesn't work, but, if I do a dump of this last piece of code, I get this result pictured below:它不起作用,但是,如果我对最后一段代码进行转储,则会得到如下图所示的结果:
I feel that i'm close to the answer, and yet so far.我觉得我已经接近答案了,但到目前为止。
Since keys
will return you a simple array, then the keys are integer from 0
to the (array | length) - 1
, to express it in Twig.由于keys
将返回一个简单的数组,因此键是从0
到(array | length) - 1
整数,用 Twig 表示。
Note that this is actually the same behaviour as PHP, when you define an array like请注意,当您定义一个数组时,这实际上与 PHP 的行为相同
['foo', 'bar', 'baz']
that would be strictly equivalent to这将严格等同于
[0 => 'foo', 1 => 'bar', 2 => 'baz']
So in your case, since you only have one element in the array you can use array[0]
or array.0
.因此,在您的情况下,由于数组中只有一个元素,因此您可以使用array[0]
或array.0
。
All together, this would work:总之,这将起作用:
{{ (app.session.get('teams').team_1 | keys).0 }}
Could be tested from https://twigfiddle.com/b6iy8i可以从https://twigfiddle.com/b6iy8i测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.