代码之家  ›  专栏  ›  技术社区  ›  JochenJung

带点输入键的Smarty数组

  •  5
  • JochenJung  · 技术社区  · 14 年前

    我在PHP中有一个数组,如下所示:

    $config['detailpage.var1']
    $config['detailpage.var2']
    $config['otherpage.var2']
    $config['otherpage.var2']
    ...
    

    要在Smarty中访问它,我愿意

    $smarty->assign('config', $config);
    

    使用此模板:

    {$config.detailpage.var1}
    

    不幸的是,这不起作用,因为我的数组键“detailpage.var1”中有一个点,对于Smarty来说,它是数组元素的定界符。 由于我不想重写我的配置数组(因为它在许多其他地方都有使用),我的问题是:

    有没有其他的符号可以用来表示数组键中的点? 或者我能逃脱他们?

    5 回复  |  直到 14 年前
        1
  •  2
  •   bolero    8 年前

    我在这里寻找答案之后“不小心”找到了这个问题的答案。在这个例子中,我使用主机名作为键,它总是有点。您可以用{}围绕虚线键名访问它们。 例如 {$var.foo.bar.{"my.hostname.example.com"}.ipaddress} .

    {$var.foo.bar.{$var.bingo}}

        2
  •  7
  •   Zsolti    14 年前

    这不是最聪明的解决方案,但它应该可以工作:

    {assign var=myKey value="detailpage.var1"}
    {$config.$myKey}
    
        3
  •  3
  •   RobertPitt    14 年前

    您可以重新格式化关联数组中的键以符合智能编译器正则表达式。

    $configS = array();
    foreach($config as $key => $value)
    {
        $key = str_replace('.','_',$key);
        $configS[$key] = $value;
    }
    $smarty->assign('config', $configS);
    

    或者

    $configS = array();
    foreach($config as $key => $value) $configS[str_replace('.','_',$key)] = $value;
    $smarty->assign('config', $configS);
    

    现在你可以用 {$config.detailpage_var1} 相反,只需替换 . _ .


    function cleanKeysForSmarty(&item,$key)
    {
        return array(str_replace('.','_',$key) => $value);
    }
    $smarty->assign("config",array_walk_recursive($config,'cleanKeysForSmarty'));
    

    一些类似的东西。

        4
  •  2
  •   Naktibalda    14 年前

        5
  •  0
  •   Marcelo Braz Rodrigues    8 年前

    用途:

    {$array[“key.with.dot”]}

    或:

    {$array[“key.with.dot”][“subkey”]}