开发者

Smarty array with dot in key

开发者 https://www.devze.com 2023-01-07 11:19 出处:网络
I have an array in PHP that looks like this: $config[\'detailpage.var1\'] $config[\'detailpage.var2\'] $config[\'otherpage.var2\']

I have an array in PHP that looks like this:

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

To access it in Smarty I would do

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

With this template:

{$config.de开发者_Go百科tailpage.var1}

Unfortunately this does not work, due to the dot in my array key "detailpage.var1", which for Smarty is the delimitor for the array elements. As I don't want to rewrite my config array (cause it is used in many other places), my question is:

Is there any other notation I could use that works with the dots in the array keys? Or can I somehow escape them?


Not the smartest solution but it should work:

{assign var=myKey value="detailpage.var1"}
{$config.$myKey}


You can reformat the keys in the associative array to comply with Smart Compiler Regex'es.

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

OR

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

Now you can use {$config.detailpage_var1} instead, just substitute the . with a _.


Walk the array,

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

Something along those lines.


I've "accidentally" found the answer to this question after I was looking myself for an answer here. In this case I'm using hostnames as keys which always have dots. You can access them with {} around the dotted key name. e.g. {$var.foo.bar.{"my.hostname.example.com"}.ipaddress} .

This "escaped" syntax can also be used in cases where you have to expand a variable that contains a dot. e.g. {$var.foo.bar.{$var.bingo}}


Try using array notation {$config['detailpage.var1']} or {$config[detailpage.var1]}.


Use:

{$array["key.with.dot"]}

Or:

{$array["key.with.dot"]["subkey"]}

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号