More efficient way to parse multi-dimensional array?
Posted: Mon Jun 13, 2011 1:41 am
I'm sure there is a much more efficient way to do this, can you help?
Example:
And the code to parse the multi-dimensional array:
In short, I want to pass n number of arguments to a function: get_val(n arguments...) and have it parse a multi-dimensional array to find the value.
If I knew it would be only 2 arguments, I could easily do $_SESSION[$arg1][$arg2], but since the number of arguments will be unknown, how do you parse an array like that?
Example:
Code: Select all
#Example Array
print_r($_SESSION);
Array
(
[global] => Array
(
[user_id] => 1
)
[authentication] => Array
(
[last_impress] => 1307943328
[token] => 1b20e459d77103ffc2c79c19300c12f2
)
)Code: Select all
<?php
function get_val()
{
$subject = $_SESSION;
foreach(func_get_args() as $key) {
if($subject)
$subject = parse_key($key, $subject);
}
return $subject;
}
function parse_key($key, $subject)
{
if(array_key_exists($key, $subject))
return $subject[$key];
else
return false;
}
print get_val('global', 'user_id'); // 1
print get_val('authentication', 'token'); // 1b20e459d77103ffc2c79c19300c12f2
?>If I knew it would be only 2 arguments, I could easily do $_SESSION[$arg1][$arg2], but since the number of arguments will be unknown, how do you parse an array like that?