I’m building a small template system and i’m looking for a way to invoke multidimensional associative arrays using dots. For example:
$animals = array(
'four-legged' => array (
'cute' => 'no',
'ugly' => 'no',
'smart' => array('best' => 'dog','worst' => 'willy')
),
'123' => '456',
'abc' => 'def'
);
Then, in my template, if I wanted to show ‘dog’, I would put:
{a.four-legged.smart.best}
Well, given a string with
four-legged.smart.worst:So you can call:
And if you want to write elements, it’s not much harder (you just need to use references, and a few checks to default the values if the path doesn’t exist)…:
Edit: Since this is in a template system, it may be worth while “compiling” the array down to a single dimension once, rather than traversing it each time (for performance reasons)…
So that would convert:
Into
Then your lookup just becomes
$value = isset($compiledArray[$path]) ? $compiledArray[$path] : '';instead of$value = getElementFromPath($array, $path);It trades pre-computing for inline speed (speed within the loop)…