如何以编程方式构建数组/对象调用[关闭]
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?
我正在开发一个Drupal模块,允许用户在其视图中使用超全局变量作为过滤器。 他们需要能够进入他们想要使用的变量的字段,然后我的函数需要去检索该变量的值。 如果您只允许一个级别,并且只允许数组,这很容易。 但是我想允许多个级别,甚至更好,允许它们访问对象和/或数组。 p>
因此,如果用户选择SESSION,然后输入: ['anarray'] ['anotherlevel'] ['something'] p>
我的函数将获得以下值: $ _SESSION ['anarray'] ['anotherlevel'] [ '某事'] p>
如果用户输入的内容更好: ['anarray'] - > anotherlevel->某事['morethings'] p >
我的函数将得到以下变量: $ _SESSION ['anarray'] - > anotherlevel->某事['morethings'] p>
等等。 对于更清晰的代码,如果他们只能使用+和 - 来分别表示数组和对象,那就更好了。 所以最后一个例子输入为: + anarray-anotherlevel-something + morethings p>
任何想法? p> div>
$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;