有人看到以下功能有什么问题吗? (编辑:不,我认为没有任何错误,我只是仔细检查,因为这将插入一个非常常见的代码路径。)
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变量。
答案 0 :(得分: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;
}
答案 1 :(得分:1)
看看这个:https://gist.github.com/elfet/4713488
$dn = new DotNotation(['bar'=>['baz'=>['foo'=>true]]]);
$value = $dn->get('bar.baz.foo'); // $value == true
$dn->set('bar.baz.foo', false); // ['foo'=>false]
$dn->add('bar.baz', ['boo'=>true]); // ['foo'=>false,'boo'=>true]
这个类也有PHPUnit测试。
答案 2 :(得分:0)
我没有看到该代码有任何问题。我也测试了它。
这会回答你的问题吗?
编辑:这是恕我直言,稍微好一些。它不使用递归,并且在访问非数组的子节点时返回null。
function getNestedVar(array $array, $name) {
$name = explode('.', $name);
foreach($name as $namePart) {
if (is_array($array)) return null;
if (!isset($array[$name])) return null;
$array = $array[$name];
}
return $array;
}
干杯
答案 3 :(得分:0)
这种筑巢有多深? PHP对递归有限制,似乎是ca. 2 ^ 16。刚刚测试了这个并且递归深度为65420 PHP(5.2.9)无声地失败(没有错误)。
答案 4 :(得分:0)
在当前形式中,如果一个或多个元素不存在,则不会显示错误/警告
error_reporting(E_ALL|E_STRICT); ini_set('display_errors', 1);
$x = array();
getNestedVar($x, '1.2.3.4');
echo 'done.';
(用php 5.3.1 / win32测试)。
出于某种原因,访问getNestedVar($context[$pieces[0]]...
中的不存在的元素不会引发警告消息,这使得调试和查找例如很难一个错字。
答案 5 :(得分:0)
为什么你不只是使用html .. name="fruit[orange]"
就足以制作一个数组。
答案 6 :(得分:0)
看看@ http://github.com/projectmeta/Stingray
允许通过点符号/语法读取和写入数组。