JochenJung JochenJung - 6 months ago 54
PHP Question

Smarty array with dot in key

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.detailpage.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?

Answer

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.