PHP - 使用点语法查找数组内容

Nic*_*ole 4 php arrays smarty multidimensional-array

有没有人看到以下功能有什么问题?(编辑:不,我认为没有任何错误,我只是仔细检查,因为这将插入一个非常常见的代码路径.)

function getNestedVar(&$context, $name) {
    if (strstr($name, '.') === FALSE) {
        return $context[$name];
    } else {
        $pieces = explode('.', $name, 2);
        return getNestedVar($context[$pieces[0]], $pieces[1]);
    }
}
Run Code Online (Sandbox Code Playgroud)

这将基本上转换:

$data, "fruits.orange.quantity"
Run Code Online (Sandbox Code Playgroud)

成:

$data['fruits']['orange']['quantity']
Run Code Online (Sandbox Code Playgroud)

对于上下文,这是我在Smarty中构建的表单实用程序.我还需要表单的名称,所以我需要字符串以基于键的形式,并且不能直接访问Smarty中的Smarty变量.

Gum*_*mbo 7

尝试迭代方法:

function getNestedVar(&$context, $name) {
    $pieces = explode('.', $name);
    foreach ($pieces as $piece) {
        if (!is_array($context) || !array_key_exists($piece, $context)) {
            // error occurred
            return null;
        }
        $context = &$context[$piece];
    }
    return $context;
}
Run Code Online (Sandbox Code Playgroud)