Twig 解析数组并按键检查
Twig parse array and check by key
我正在尝试查看数组是否有键。第一种情况 returns 2 结果 1-5 和 ,而第二种情况似乎工作正常。
知道为什么会这样吗?
{% set options = {'1' : '1' , '1-5' : '5' , '1-12' : '12' } %}
{% set selected = '1-5' %}
Wrong check
{% for k,v in options %}
{% if k == selected %}
{{ k }}
{% endif %}
{% endfor %}
Right
{% for k,v in options %}
{% if k|format == selected|format %}
{{ k }}
{% endif %}
{% endfor %}
Twig 将在以下 PHP 片段中编译 "wrong check":
if (($context["k"] == (isset($context["selected"]) || array_key_exists("selected", $context) ? $context["selected"] : (function () { throw new RuntimeError('Variable "selected" does not exist.', 6, $this->source); })()))) {
简化为
if ($context["k"] == $context["selected"])
因为 context["k"]
的类型(对于第一次迭代)是整数,PHP
也会将等式的右侧部分类型转换为整数。所以等式实际上变成了:
if ((int)1 == (int)'1-5')
并将 1-5
转换为整数变为 1
,使最终等式变为:
1 == 1
结果为 true
顺便说一下,您可以使用以下 PHP
代码段
来测试第一个键被视为整数的事实
<?php
$foo = [ '1' => 'bar', ];
$bar = '1-5';
foreach($foo as $key => $value) {
var_dump($key); ## output: (int) 1
var_dump($key == $bar); ## output: true
}
我正在尝试查看数组是否有键。第一种情况 returns 2 结果 1-5 和 ,而第二种情况似乎工作正常。
知道为什么会这样吗?
{% set options = {'1' : '1' , '1-5' : '5' , '1-12' : '12' } %}
{% set selected = '1-5' %}
Wrong check
{% for k,v in options %}
{% if k == selected %}
{{ k }}
{% endif %}
{% endfor %}
Right
{% for k,v in options %}
{% if k|format == selected|format %}
{{ k }}
{% endif %}
{% endfor %}
Twig 将在以下 PHP 片段中编译 "wrong check":
if (($context["k"] == (isset($context["selected"]) || array_key_exists("selected", $context) ? $context["selected"] : (function () { throw new RuntimeError('Variable "selected" does not exist.', 6, $this->source); })()))) {
简化为
if ($context["k"] == $context["selected"])
因为 context["k"]
的类型(对于第一次迭代)是整数,PHP
也会将等式的右侧部分类型转换为整数。所以等式实际上变成了:
if ((int)1 == (int)'1-5')
并将 1-5
转换为整数变为 1
,使最终等式变为:
1 == 1
结果为 true
顺便说一下,您可以使用以下 PHP
代码段
<?php
$foo = [ '1' => 'bar', ];
$bar = '1-5';
foreach($foo as $key => $value) {
var_dump($key); ## output: (int) 1
var_dump($key == $bar); ## output: true
}