Get Array value by string of keys
I'm building a template engine for my next project, which is going great. It replaces {tag}
with a corresponding value.
I want {tag[0][key]}
to be replaced as well. All I need to know is how to get the value, if I have the string representation of the array and key, like this:
$arr = array(
0 => array(
'key' => 'value'
),
1 => array(
'key' =>开发者_StackOverflow 'value2'
)
);
$tag = 'arr[0][key]';
echo($$tag);
This is a very simple version of the problem, I hope you understand it. Or else I would be happy to answer any questions about it.
I agree that there is no need to reinvent the wheel: PHP itself was born as a template engine, and is still good at doing this:
<?php echo $arr[0][key]; ?>
It even used to have the now deprecated form
<?= $arr[0][key] ?>
In any case you could do the following
$keys = array();
preg_match_all('|\[([^\]]*)\]|', $tag, $keys);
$result = $arr;
foreach ($keys[1] as $key) {
$result = $result[$key];
}
echo "$result\n";
精彩评论