Reputation: 138
is there an easy, non-eval-using method for getting a reference to an element of a multidimensional array? 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.
Upvotes: 6
Views: 2419
Reputation: 2143
This should do what you are after:
function &getSessionReference($keyStr, &$session) {
$keys = explode('.', $keyStr);
$temp = &$session;
foreach ($keys as $key) {
$temp = &$temp[$key];
}
return $temp;
}
$_SESSION['1']['4']['2'] = [];
$arrReference = &getSessionReference('1.4.2', $_SESSION);
$arrReference['foo'] = 'bar';
echo json_encode($_SESSION);
// {"1":{"4":{"2":{"foo":"bar"}}}}
Upvotes: 0
Reputation: 31813
$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
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 =&
.
Upvotes: 7
Reputation: 365
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);
p.s.: this does not actually return the reference but it serves your needs.
Upvotes: 1