PHP - 用点语法查找数组内容 [英] PHP - lookup array contents with dot syntax
本文介绍了PHP - 用点语法查找数组内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有谁看到什么错用下面的函数? (修改:不,我觉得没有什么是错的,我只是双重检查,因为这会被插入到一个很普通的code路径)
Does anybody see anything wrong with the following function? (Edit: no, I don't think anything is wrong, I am just double-checking since this will be inserted into a very common code path.)
function getNestedVar(&$context, $name) {
if (strstr($name, '.') === FALSE) {
return $context[$name];
} else {
$pieces = explode('.', $name, 2);
return getNestedVar($context[$pieces[0]], $pieces[1]);
}
}
这将从根本上转换:
$data, "fruits.orange.quantity"
到
$data['fruits']['orange']['quantity']
有关的背景下,这是一个实用的形式,我建设Smarty的。我需要的名称,形式也因此我需要的字符串是在一个基于密钥的形式,不能直接访问的Smarty Smarty的变量。
For context, this is for a form utility I am building in Smarty. I need the name for the form also so I need the string to be in a key-based form, and can't directly access the Smarty variable in Smarty.
推荐答案
尝试迭代的方法:
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;
}
这篇关于PHP - 用点语法查找数组内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文