I am retrieving some data from a database and this data references array keys, with this data I need to find the value based off of this dynamic data.
The code:
$a['field'] examples:
$a['field'] = 'foo';
$a['field'] = 'foo.bar';
$a['field'] = 'foo.bar.baz';
The periods in the above values are deliminators to separate the keys of the referencing array.
Primary Code:
$field_value = null;
if (strpos($a['field'], '.') !== false) {
$str = null;
$the_fields = explode('.', $a['field']);
// Build string
foreach ($the_fields as $val) {
$str .= "['" . $val . "']";
}
$field_value = get_fields( 'option' ){$str};
} else {
$field_value = get_fields( 'option' )[$a['field']];
}
Problem is with this section:
foreach ($the_fields as $val) {
$str .= "['" . $val . "']";
}
$field_value = get_fields( 'option' ){$str};
I get a Undefined index: ['foo']['bar']
.
I believe this is because it is treating the code as verbatim and literally looking for an index named "['foo']['bar']" including the brackets.
I'm sure it would be easy enough to loop through and key the values one by one to avoid building a string like this to call, but I'm hoping I can do it with just a single assignment.
Is there a way to do this?