php - Twig 解析数组并按键检查

标签 php twig

我正在尝试查看数组是否有键。第一种情况返回 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 %}

https://twigfiddle.com/c6m0h4

最佳答案

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
}

demo

关于php - Twig 解析数组并按键检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434841/

相关文章:

php - 在 php 中从 Markdown 生成目录

php - 如何在 Laravel 中查询自定义键?

php - is_null 函数在我的 if 语句中无法正常工作

php - Twig 函数返回一个模板

php - Twig:更新代码前面的变量

php - 使用 Silex/SilexExtensions 和 Assetic 在 Twig 中动态 CSS/Javascript

javascript - 如何在适用于 Android 平台的 PhoneGap 应用程序中接收即时通知,告知您收件箱中有来自管理员的新消息

html - Twig 和 CodeIgniter 表单渲染问题。表单显示为字符串而不是 HTML 表单

Symfony2 获取在 twig 中调用的 Action 请求

javascript - 如何编辑/删除同位素库中的 `show all` View ?