我正在尝试查看数组是否有键。第一种情况返回 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 代码片段中的“错误检查”:
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
}
关于php - Twig 解析数组并按键检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434841/