PHP has a handy feature to allow to "pre-create" array keys in a form:
<input type="text" name="settings[store][this][here]" />
Now, in a database I have stored the "location" of a certain value, using this field value:
[store][this][here]
I want to recall this value in an array call, like this:
echo $result[settings][database-field];
which would then become:
echo $result[settings][store][this][here];
How can I construct my call to do this?
I have tried the following, but to no avail:
echo $result[settings][$row[database-field]];
echo $result[settings][${$row[database-field]}]
You could use regular expressions to parse the keys from the location (parsing will dynamically adapt to keys of different depths > 0):
$result['settings'] = ['store'=>['this'=>['here'=>'stored value']]];
$location = "[store][this][here]";
preg_match_all('/\[(\w+)\]/',$location, $matches);
$keys = $matches[1];
$value = $result['settings'][current($keys)];
while(next($keys)) $value = $value[current($keys)];
echo $value; // 'stored value'
demo
I would be careful about using eval() on user-supplied input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With