I am having trouble figuring out a way to simply parse a string input and find the correct location within a multidimensional array.
I am hoping for one or two lines to do this, as the solutions I have seen rely on long (10-20 line) loops.
Given the following code (note that the nesting could, in theory, be of any arbitrary depth):
function get($string)
{
$vars = array(
'one' => array(
'one-one' => "hello",
'one-two' => "goodbye"
),
'two' => array(
'two-one' => "foo",
'two-two' => "bar"
)
);
return $vars[$string]; //this syntax isn't required, just here to give an idea
}
get("two['two-two']"); //desired output: "bar". Actual output: null
Is there a simple use of built-in functions or something else easy that would recreate my desired output?
Considering
$vars
being your variables you would like to getone['one-one']
ortwo['two-two']['more']
from (Demo):This is lexing the string into key tokens and then traverse the
$vars
array on the keyed values while the$vars
array has been turned into a function.Older Stuff:
Overload the array with a function that just eval's:
If you're not a fan of eval, change the implementation: