I'm developing a Drupal module that allows users to use a superglobal variable as a filter in their view. They need to be able to enter into a field the variable they want to use, and then my function needs to then go and retrive the value of that variable. This is easy enough if you only allow one level, and only array. But I would like to allow for multiple levels, and even better, allow them to access objects and/or arrays.
So if the user were to choose SESSION, and then enter: ['anarray']['anotherlevel']['something']
my function would then get the value of: $_SESSION['anarray']['anotherlevel']['something']
Even better would be if the user could enter something like: ['anarray']->anotherlevel->something['morethings']
my function would get the variable of: $_SESSION['anarray']->anotherlevel->something['morethings']
And so on. For even cleaner code, if they could just use + and - to represent an array and object respectively, that would be even better. So the last example would be entered as: +anarray-anotherlevel-something+morethings
Any ideas?
$path = 'foo.bar.baz';
$value = $_SESSION;
foreach (explode('.', $path) as $key) {
if (is_array($value) && array_key_exists($key, $value)) {
$value = $value[$key];
} else if (is_object($value) && property_exists($value, $key)) {
$value = $value->$key;
} else {
throw new InvalidArgumentException(sprintf('The path %s does not exist', $path));
}
}
echo $value;
You'll have to parse the inputted string looking for +
and -
and deal with them. It's really not that hard. To parse the string you start to read each character and check if it's a +
or -
. If it's one of them you start recording all the characters from there to the next +
/-
sign and record the indentation with $current
(initially to $current = $_SESSION
) so that if you have read +
and then abc
you update $current
with:
$current = (isset($current['abc'])) ? isset($current['abc'] : NULL;