Get Array value by string of keys

风流意气都作罢 提交于 2019-12-25 14:48:26

问题


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' => '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.


回答1:


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";


来源:https://stackoverflow.com/questions/5127714/get-array-value-by-string-of-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!