通过键字符串获取数组值 [英] Get Array value by string of keys

查看:47
本文介绍了通过键字符串获取数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为下一个项目构建模板引擎,进展非常顺利。它将 {tag} 替换为相应的值。

I'm building a template engine for my next project, which is going great. It replaces {tag} with a corresponding value.

我也希望替换 {tag [0] [key]} 。我需要知道的是如何获取值,如果我具有数组和键的字符串表示形式,就像这样:

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.

推荐答案

我同意没有必要重新发明轮子: PHP本身就是作为模板引擎而诞生的,并且仍然擅长于此:

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

这篇关于通过键字符串获取数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆