0

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?

Brett
  • 19,449
  • 54
  • 157
  • 290
  • 1
    its called dot path/notation/prop.. in your code you would need use eval. you dont need string [, ] etc as you have $val which can be used to traverse the result of $field_value's, is very much a dupe of https://stackoverflow.com/questions/27929875/how-to-access-and-manipulate-multi-dimensional-array-by-key-names-path – Lawrence Cherone Sep 21 '20 at 20:49
  • I was trying to avoid having to use `eval` TBH, but thanks for the link. – Brett Sep 21 '20 at 20:52
  • 1
    Converting this dot-notation to a multi-dim array has been asked here before. I am not sure that I agree with close this page https://stackoverflow.com/q/9635968/2943403 (**there is no `eval()` called**) with another page which was asked 3 year later. – mickmackusa Sep 21 '20 at 21:29

0 Answers0