[英]PHP - Get a reference to an element from a multidimensional array by using string as key
is there an easy, non-eval-using method for getting a reference to an element of a multidimensional array? 是否有一个简单的,非eval-using方法来获取对多维数组元素的引用? The key should be passed as a string. 密钥应作为字符串传递。
Here's an example: 这是一个例子:
getSessionReference('1.4.2', $arrReference);
should return a reference to 应该返回一个引用
$_SESSION['1']['4']['2']
and so a call like 所以打电话就好
$arrReference['foo'] = 'bar';
would change it to 会改变它
$_SESSION['1']['4']['2']['foo'] = 'bar'
Any ideas? 有任何想法吗?
Thanks in advance. 提前致谢。
$arr[5][6][7] = 111;
$cursor =& $arr;
foreach (explode('.', '5.6') as $key) {
$cursor =& $cursor[$key];
}
var_dump($arr);
var_dump($cursor);
$cursor['foo'] = 5;
var_dump($arr);
var_dump($cursor);
http://codepad.viper-7.com/XUEhMj http://codepad.viper-7.com/XUEhMj
or in function form 或以功能形式
function & getSessionRef($keyPath) {
$cursor =& $_SESSION;
foreach (explode('.', $keyPath) as $key) {
$cursor =& $cursor[$key];
}
return $cursor;
}
$cursor =& getSessionRef('a.6');
btw - I used the php feature named references in that code, where you see the ampersand like =&
. 顺便说一句 - 我在该代码中使用了名为引用的php功能,在那里你可以看到&符号和=&
。
Use pass-by-reference. 使用传递引用。
function getReference($key, &$arr)
{
$e = explode('.', $key);
foreach ($_SESSION[$e[0]][$e[1]][$e[2]] as $k => &$v)
$arr[$k] = $v;
}
$arr = array();
getReference("1.4.2", $arr);
ps: this does not actually return the reference but it serves your needs. ps:这实际上不会返回引用,但它可以满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.